@reticlehq/engine 3.3.0 → 3.5.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.
package/NOTICE ADDED
@@ -0,0 +1,5 @@
1
+ Reticle
2
+ Copyright 2026 Reticle Labs
3
+
4
+ This product includes software developed at Reticle Labs.
5
+ Licensed under the Apache License, Version 2.0.
@@ -1,4 +1,4 @@
1
- import { ContradictionKind, EventType, REQUEST_SHAPE_FIELD, isAbsenceDerived, isSameDocument, isSameEditEpoch, } from '@reticlehq/core';
1
+ import { ContradictionKind, EventType, NEXT_ACTION_FIELD, REQUEST_SHAPE_FIELD, isAbsenceDerived, isSameDocument, isSameEditEpoch, } from '@reticlehq/core';
2
2
  import { describeSuperseded } from '../question/predicate/observed-in-window.js';
3
3
  import { describe, isMutating, isSameDocumentHashAnchor, isSteadyCadence, netCall, recoveredByRetry, splitForeignTraffic, } from './contradiction-evidence.js';
4
4
  import { findStaleResponses } from './stale-response.js';
@@ -8,40 +8,28 @@ import { findUnitMismatches } from './unit-mismatch.js';
8
8
  import { asString } from '@reticlehq/core';
9
9
  import { matchesDeclaredFailure } from '../question/declared.js';
10
10
  import { runRegisteredFolds } from './contradiction-folds.js';
11
- /**
12
- * The contradiction hunter.
13
- *
14
- * Every other check reads ONE channel and asks "did something bad happen there?". This asks what a
15
- * person watching the screen structurally cannot: do the channels DISAGREE? The DOM, the store, the
16
- * app's own signals, the console and the network arrive in one causally ordered window, so the case
17
- * where the screen says one thing and the network says the opposite is visible — and that gap is
18
- * where false greens live, because a screenshot, a DOM assertion and a human all agree there.
19
- *
20
- * Pure: a window of events in, findings out. No session, no IO, no clock.
21
- */
22
- /**
23
- * What this request CARRIED, as far as the record knows — `undefined` when it does not know.
24
- *
25
- * The page's shape fingerprint first: it is present on every request from an instrumented page,
26
- * including the overwhelming majority where body capture is off. A captured body is the fallback for
27
- * a realm that records one without a fingerprint (desktop IPC). Neither means the record does not
28
- * say what this request carried — a body the page could not read as text, or an SDK too old to
29
- * compute a fingerprint — and that is an ABSENCE of identity, not an identity shared with every
30
- * other silent request.
31
- */
32
11
  function identityOf(event) {
12
+ const action = asString(event.data[NEXT_ACTION_FIELD]);
33
13
  const shape = asString(event.data[REQUEST_SHAPE_FIELD]);
34
- if (shape !== undefined && 0 !== shape.length)
35
- return shape;
36
14
  const body = asString(event.data['requestBody']);
37
- return body === undefined || 0 === body.length ? undefined : body;
15
+ const carried = shape !== undefined && 0 !== shape.length
16
+ ? shape
17
+ : body === undefined || 0 === body.length
18
+ ? undefined
19
+ : body;
20
+ if (action === undefined || 0 === action.length) {
21
+ return carried === undefined ? undefined : { key: carried, carried: true };
22
+ }
23
+ return carried === undefined
24
+ ? { key: action, carried: false }
25
+ : { key: `${action}:${carried}`, carried: true };
38
26
  }
39
27
  /** Split calls to one endpoint into the sets that sent the same thing. Callers check first that
40
28
  * every identity is known; an unknown one would otherwise pool with every other unknown. */
41
29
  function groupByIdentity(calls) {
42
30
  const byIdentity = new Map();
43
31
  for (const call of calls) {
44
- const key = call.identity ?? '';
32
+ const key = call.identity?.key ?? '';
45
33
  byIdentity.set(key, [...(byIdentity.get(key) ?? []), call]);
46
34
  }
47
35
  return [...byIdentity.values()];
@@ -589,6 +577,10 @@ function findWindowContradictions(allEvents, options) {
589
577
  const landed = group.filter((c) => c.landed).length;
590
578
  if (times.length < 2)
591
579
  continue;
580
+ // The identity also has to say WHICH PAYLOAD, not only which action ran. A group held
581
+ // together by an action id over bodies the record could not read keeps the uncertainty in
582
+ // its wording: two runs of one action can carry different form data.
583
+ const carriedKnown = group.every((c) => true === c.identity?.carried);
592
584
  // A DOUBLE SUBMIT is a write that landed twice. Two attempts of which one failed is a RETRY,
593
585
  // and the field case is the commonest retry there is: a 401 that refreshed a token and went
594
586
  // again, one row created, reported here as `duplicate-request ×2`. Two attempts that both
@@ -616,10 +608,10 @@ function findWindowContradictions(allEvents, options) {
616
608
  claim: related
617
609
  ? 'one user action was performed'
618
610
  : 'the assertion did not name this endpoint',
619
- counter: identified
611
+ counter: carriedKnown
620
612
  ? `the same write fired ${count} times`
621
613
  : `this endpoint was written to ${count} times`,
622
- detail: identified
614
+ detail: carriedKnown
623
615
  ? `${label} ×${count}`
624
616
  : `${label} ×${count} — nothing on the record says what these requests carried, ` +
625
617
  'so whether they were one write repeated or different writes could not be established',
@@ -91,6 +91,20 @@ function isIdentityKey(key) {
91
91
  const lower = key.toLowerCase();
92
92
  return 'id' === lower || lower.endsWith('_id');
93
93
  }
94
+ /**
95
+ * Keys that name an optimistic-concurrency token, not a persisted attribute. A compare-and-set
96
+ * write sends the version it read and expects the server to bump it — the changed value in the
97
+ * response is the proof the write applied, not evidence the write was ignored, the same way a
98
+ * create's assigned `id` is not a dropped field.
99
+ */
100
+ function isVersionKey(key) {
101
+ const lower = key.toLowerCase();
102
+ return ('version' === lower ||
103
+ '_version' === lower ||
104
+ 'etag' === lower ||
105
+ 'rev' === lower ||
106
+ 'revision' === lower);
107
+ }
94
108
  /**
95
109
  * Every scalar value the response carries for each key, at any depth.
96
110
  *
@@ -273,6 +287,8 @@ export function findEchoMismatches(events, actionSince) {
273
287
  continue;
274
288
  if (isIdentityKey(key))
275
289
  continue;
290
+ if (isVersionKey(key))
291
+ continue;
276
292
  const values = echoed.get(key);
277
293
  // Not echoed at all = no evidence either way. Only a key the server chose to report back can
278
294
  // contradict the request, and silence is not a contradiction.
@@ -16,7 +16,7 @@
16
16
  * So these are the kinds worth evaluating BEFORE the act, to find out whether the green means
17
17
  * anything.
18
18
  */
19
- import { PredicateKind } from '@reticlehq/core';
19
+ import { PredicateKind, compareSourceClauses } from '@reticlehq/core';
20
20
  import { asksForComparison } from './baseline.js';
21
21
  export function readsDomState(predicate) {
22
22
  switch (predicate.kind) {
@@ -55,6 +55,10 @@ export function readsDomState(predicate) {
55
55
  return predicate.predicates.some(readsDomState);
56
56
  case PredicateKind.NOT:
57
57
  return readsDomState(predicate.predicate);
58
+ // A comparison between two LIVE readings (text, a store) can already agree before the click, and
59
+ // then it proves nothing about the click. A `net` or `signal` side is floored like any other.
60
+ case PredicateKind.COMPARE:
61
+ return compareSourceClauses(predicate).some(readsDomState);
58
62
  default:
59
63
  return false;
60
64
  }
@@ -47,11 +47,17 @@ export function gapsForAction(facts) {
47
47
  // assertion about state to an agent that made no such assertion is a false explanation, and a
48
48
  // gap nobody can act on is worse than no gap: it costs the trip and teaches the wrong lesson.
49
49
  const declaredNothing = false === facts.hasCapabilities;
50
+ // `stateUnwatched` means no SUBSCRIBABLE store, not no store (#1146). A bare getter —
51
+ // `registerStore('app', () => state)` — is registered and readable, and a `state` assertion is
52
+ // answered by reading it on demand, so "no store is registered" contradicted a passing verdict
53
+ // in the same response. Nothing here can tell that app from one that registered nothing, or from
54
+ // a React app whose only store is Reticle's own `__reticle_renders` getter, so the sentence says
55
+ // only what is true of all three.
50
56
  gaps.push(instrumentationGap(InstrumentationGapKind.NO_STORE_REGISTERED, declaredNothing
51
57
  ? 'this app declared no capabilities at all, so no state can be read from it'
52
- : 'no store is registered, and this assertion was about state', declaredNothing
58
+ : 'no subscribable store is registered, and this assertion was about state', declaredNothing
53
59
  ? 'every verdict here rests on what the DOM happens to show, and reticle_state will stay empty however many flows are driven'
54
- : 'the assertion could not be answered from the deterministic channel and had to fall back to what the DOM happens to show'));
60
+ : 'no state change is observed, so state, when it can be read at all, is read only as it stands and never seen changing'));
55
61
  }
56
62
  // The app moved and said nothing, and Reticle could not prove the outcome another way.
57
63
  if (facts.domMutated && 0 === facts.signalsFired && true !== facts.proved) {
@@ -15,7 +15,7 @@
15
15
  * It rides in `because`, beside `verifiedReason`, rather than in a field of its own: the verdict has
16
16
  * one sentence an agent is known to read, and a caveat parked anywhere else is a caveat nobody reads.
17
17
  */
18
- import { PredicateKind } from '@reticlehq/core';
18
+ import { PredicateKind, compareSourceClauses } from '@reticlehq/core';
19
19
  /** Enough to recognise the one that is stuck; not so many that a chatty window eats the verdict. */
20
20
  const MAX_LISTED_REQUESTS = 3;
21
21
  /**
@@ -44,6 +44,8 @@ export function describeWaitTarget(predicate) {
44
44
  return 'a console message';
45
45
  case PredicateKind.ANIMATION:
46
46
  return predicate.name === undefined ? 'an animation' : `animation '${predicate.name}'`;
47
+ case PredicateKind.COMPARE:
48
+ return `${predicate.left.from} and ${predicate.right.from} readings to agree`;
47
49
  case PredicateKind.ALL_OF:
48
50
  return `all of (${predicate.predicates.map(describeWaitTarget).join('; ')})`;
49
51
  case PredicateKind.ANY_OF:
@@ -71,6 +73,10 @@ export function namedNetIsInFlight(predicate, stillInFlight) {
71
73
  for (const child of p.predicates)
72
74
  walk(child);
73
75
  return;
76
+ case PredicateKind.COMPARE:
77
+ for (const child of compareSourceClauses(p))
78
+ walk(child);
79
+ return;
74
80
  case PredicateKind.NET: {
75
81
  if (undefined === p.urlContains || 0 === p.urlContains.length)
76
82
  return;
@@ -17,7 +17,7 @@
17
17
  * opposite of a consequence — honouring either would suppress a real finding on the strength of
18
18
  * something that never happened. Pure: a predicate in, a description out.
19
19
  */
20
- import { PredicateKind, QueryBy } from '@reticlehq/core';
20
+ import { PredicateKind, QueryBy, compareSourceClauses } from '@reticlehq/core';
21
21
  /** Below this, a status is a success or a redirect: not a declared failure. */
22
22
  const FAILURE_STATUS_MIN = 400;
23
23
  /** Statuses that mean the caller was refused — the proof of an auth/authz denial, not a fault. */
@@ -75,6 +75,10 @@ export function declaredExpectations(predicate) {
75
75
  for (const child of p.predicates)
76
76
  walk(child);
77
77
  return;
78
+ case PredicateKind.COMPARE:
79
+ for (const child of compareSourceClauses(p))
80
+ walk(child);
81
+ return;
78
82
  case PredicateKind.NET: {
79
83
  netUrls.push(p.urlContains ?? '');
80
84
  const declaredFailure = false === p.ok || (p.status !== undefined && p.status >= FAILURE_STATUS_MIN);
@@ -138,6 +142,10 @@ export function declaresBodyIndependentChannel(predicate) {
138
142
  case PredicateKind.STATE:
139
143
  case PredicateKind.ROUTE:
140
144
  return true;
145
+ // Only through a side the body does not own. Two body fields compared with each other are
146
+ // still body evidence, and another write's unread answer stays unread beside them.
147
+ case PredicateKind.COMPARE:
148
+ return [p.left, p.right].some((side) => PredicateKind.NET !== side.from);
141
149
  case PredicateKind.ELEMENT:
142
150
  return (true !== p.absent &&
143
151
  (p.query.value !== undefined ||
@@ -1,4 +1,4 @@
1
- import { PredicateKind } from '@reticlehq/core';
1
+ import { PredicateKind, compareSourceClauses } from '@reticlehq/core';
2
2
  /**
3
3
  * Did the caller's predicate ask about registered state?
4
4
  *
@@ -20,6 +20,9 @@ export function declaresState(predicate) {
20
20
  }
21
21
  if (predicate.kind === PredicateKind.NOT)
22
22
  return declaresState(predicate.predicate);
23
+ if (predicate.kind === PredicateKind.COMPARE) {
24
+ return compareSourceClauses(predicate).some(declaresState);
25
+ }
23
26
  return false;
24
27
  }
25
28
  /**
@@ -42,5 +45,8 @@ export function declaresDom(predicate) {
42
45
  }
43
46
  if (predicate.kind === PredicateKind.NOT)
44
47
  return declaresDom(predicate.predicate);
48
+ if (predicate.kind === PredicateKind.COMPARE) {
49
+ return compareSourceClauses(predicate).some(declaresDom);
50
+ }
45
51
  return false;
46
52
  }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The `compare` predicate: read two observed values and relate them (see core's compare-source.ts).
3
+ *
4
+ * Each side resolves to one SCALAR or to a result that says why it could not. The honesty rules are
5
+ * the ones every body clause already keeps: a call that never happened, a missing element or a
6
+ * missing field is a failure, because the app did not produce what was claimed; a body that was not
7
+ * recorded, was truncated before the field, or had the field redacted is UNKNOWN, because nobody
8
+ * could have read it. Neither is ever a pass, since a comparison with a side missing compares nothing.
9
+ */
10
+ import { PredicateKind, type ReticleEvent } from '@reticlehq/core';
11
+ import { type EvalResult } from './predicate-eval-kit.js';
12
+ import type { Predicate } from './predicate-schema.js';
13
+ import type { PredicateSession } from './predicate-session.js';
14
+ type ComparePredicate = Extract<Predicate, {
15
+ kind: typeof PredicateKind.COMPARE;
16
+ }>;
17
+ export declare function evalCompare(session: PredicateSession, events: readonly ReticleEvent[], p: ComparePredicate, diagnose: boolean): Promise<EvalResult>;
18
+ export {};
@@ -0,0 +1,226 @@
1
+ /**
2
+ * The `compare` predicate: read two observed values and relate them (see core's compare-source.ts).
3
+ *
4
+ * Each side resolves to one SCALAR or to a result that says why it could not. The honesty rules are
5
+ * the ones every body clause already keeps: a call that never happened, a missing element or a
6
+ * missing field is a failure, because the app did not produce what was claimed; a body that was not
7
+ * recorded, was truncated before the field, or had the field redacted is UNKNOWN, because nobody
8
+ * could have read it. Neither is ever a pass, since a comparison with a side missing compares nothing.
9
+ */
10
+ import { CompareAs, EventType, NetBodySide, PredicateKind, REDACTED_VALUE, urlForMatch, } from '@reticlehq/core';
11
+ import { parseJsonObject, readField, redactedOnPath, str, } from './predicate-eval-kit.js';
12
+ import { evalElement, joinedText } from './predicate-element.js';
13
+ import { evalState } from './predicate-state.js';
14
+ const REMEDY_BODY_CAPTURE = 'enable it where the app calls connect(): reticle({ captureNetworkBodies: true })';
15
+ function unknown(reason) {
16
+ return { result: { pass: false, failureReason: reason, inconclusive: reason } };
17
+ }
18
+ function missing(reason, expected) {
19
+ return {
20
+ result: {
21
+ pass: false,
22
+ failureReason: reason,
23
+ observed: reason,
24
+ expected,
25
+ assertion: 'compare.source-missing',
26
+ },
27
+ };
28
+ }
29
+ function isScalar(value) {
30
+ return (null === value ||
31
+ 'string' === typeof value ||
32
+ 'number' === typeof value ||
33
+ 'boolean' === typeof value);
34
+ }
35
+ function redacted(label) {
36
+ return unknown(`${label} was ${REDACTED_VALUE} before it was recorded — a redacted field is unknown, not different`);
37
+ }
38
+ /**
39
+ * A reading that is an object or an array cannot be compared as one value, and neither can the
40
+ * redaction marker: the transport writes it for every sensitive key whatever it held, so two
41
+ * different secrets arrive as the same string and would compare equal.
42
+ */
43
+ function asScalar(value, label) {
44
+ if (REDACTED_VALUE === value)
45
+ return redacted(label);
46
+ if (isScalar(value))
47
+ return { value, label };
48
+ return unknown(`${label} is ${Array.isArray(value) ? 'an array' : 'an object'}, not a single value — point the path at one field inside it`);
49
+ }
50
+ function describeNetSource(source) {
51
+ const side = source.body ?? NetBodySide.RESPONSE;
52
+ const call = `${source.method === undefined ? '' : `${source.method.toUpperCase()} `}${source.urlContains}`;
53
+ return `${side} body of the last call to ${call} at ${JSON.stringify(source.path)}`;
54
+ }
55
+ function readNet(events, source) {
56
+ const label = describeNetSource(source);
57
+ const calls = events.filter((e) => e.type === EventType.NET_REQUEST &&
58
+ urlForMatch(e.data).includes(source.urlContains) &&
59
+ (source.method === undefined ||
60
+ str(e.data['method'])?.toUpperCase() === source.method.toUpperCase()));
61
+ // The last call is the answer the page would be showing: an earlier one has been superseded by it.
62
+ const call = calls[calls.length - 1];
63
+ if (call === undefined) {
64
+ return missing(`no call to ${source.urlContains} in this window, so there was no ${label}`, `a call matching ${source.urlContains}`);
65
+ }
66
+ const request = NetBodySide.REQUEST === source.body;
67
+ const body = str(call.data[request ? 'requestBody' : 'responseBody']);
68
+ if (body === undefined) {
69
+ return unknown(`the ${label} was not recorded, so it could not be read — ${REMEDY_BODY_CAPTURE}`);
70
+ }
71
+ const truncated = true === call.data[request ? 'requestBodyTruncated' : 'responseBodyTruncated'];
72
+ const payload = parseJsonObject(body);
73
+ if (payload === undefined) {
74
+ return truncated
75
+ ? unknown(`the ${label} was TRUNCATED before it was recorded, so the field could not be read`)
76
+ : unknown(`the body is not a JSON object, so ${label} names no field — compare reads JSON fields`);
77
+ }
78
+ if (redactedOnPath(payload, source.path))
79
+ return redacted(label);
80
+ const field = readField(payload, source.path);
81
+ if (!field.found) {
82
+ if (truncated) {
83
+ return unknown(`the ${label} was TRUNCATED before it was recorded, and the field is not in the part that was kept`);
84
+ }
85
+ const keys = field.availableKeys ?? [];
86
+ return missing(`${label} is missing${0 === keys.length ? '' : ` (keys there: ${keys.join(', ')})`}`, `a field at ${JSON.stringify(source.path)}`);
87
+ }
88
+ return asScalar(field.value, label);
89
+ }
90
+ function readSignal(events, source) {
91
+ const label = `payload of the last '${source.name}' signal at ${JSON.stringify(source.path)}`;
92
+ const fired = events.filter((e) => e.type === EventType.SIGNAL && str(e.data['name']) === source.name);
93
+ const last = fired[fired.length - 1];
94
+ if (last === undefined) {
95
+ return missing(`signal '${source.name}' never fired in this window`, `signal '${source.name}'`);
96
+ }
97
+ const payload = last.data['data'];
98
+ const record = 'object' === typeof payload && payload !== null && !Array.isArray(payload)
99
+ ? payload
100
+ : undefined;
101
+ // Signal payloads cross the same transport sanitizer as state, so a parent can be redacted too.
102
+ if (record !== undefined && redactedOnPath(record, source.path))
103
+ return redacted(label);
104
+ const field = record === undefined ? { found: false, value: undefined } : readField(record, source.path);
105
+ if (!field.found) {
106
+ return missing(`${label} is missing; the payload was ${JSON.stringify(payload)}`, label);
107
+ }
108
+ return asScalar(field.value, label);
109
+ }
110
+ async function readStore(session, source) {
111
+ const label = `state at ${JSON.stringify(source.path)}`;
112
+ const read = await evalState(session, {
113
+ kind: PredicateKind.STATE,
114
+ path: source.path,
115
+ ...(source.store === undefined ? {} : { store: source.store }),
116
+ });
117
+ if (!read.pass)
118
+ return { result: read };
119
+ const value = read.evidence?.value;
120
+ return asScalar(value, label);
121
+ }
122
+ async function readText(session, source, diagnose) {
123
+ const label = `text of ${source.scope}`;
124
+ const found = await evalElement(session, { scope: source.scope, self: true }, undefined, false, diagnose);
125
+ if (!found.pass)
126
+ return { result: found };
127
+ return { value: joinedText(found.evidence), label };
128
+ }
129
+ function readSide(session, events, source, diagnose) {
130
+ switch (source.from) {
131
+ case PredicateKind.NET:
132
+ return readNet(events, source);
133
+ case PredicateKind.SIGNAL:
134
+ return readSignal(events, source);
135
+ case PredicateKind.STATE:
136
+ return readStore(session, source);
137
+ case PredicateKind.TEXT:
138
+ return readText(session, source, diagnose);
139
+ }
140
+ }
141
+ /**
142
+ * A thousands-grouped number or a plain one. A comma counts as a separator only in groups of three,
143
+ * so `11,87` (a decimal comma) reads as two numbers, not as 1187 — and two numbers are refused.
144
+ */
145
+ const NUMBER_TOKEN = /-?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?/g;
146
+ /** One number out of a reading, or why there is not exactly one. */
147
+ function numberOf(value) {
148
+ if ('number' === typeof value)
149
+ return Number.isFinite(value) ? { n: value } : { why: 'is not finite' };
150
+ if ('string' !== typeof value)
151
+ return { why: `is ${JSON.stringify(value)}, not a number` };
152
+ const tokens = value.match(NUMBER_TOKEN) ?? [];
153
+ const [only] = tokens;
154
+ if (1 !== tokens.length || only === undefined) {
155
+ return {
156
+ why: `holds ${String(tokens.length)} numbers in ${JSON.stringify(value)}, so which one was meant is a guess — narrow the scope to one value`,
157
+ };
158
+ }
159
+ return { n: Number(only.replace(/,/g, '')) };
160
+ }
161
+ /**
162
+ * A few units in the last place: the noise of arithmetic done in binary (`0.1 + 0.2` against the
163
+ * `0.3` a page prints). Relative to the operands, so it stays below one part in 10^15 — two distinct
164
+ * decimals of 15 significant digits never fall inside it, which is every amount a double can hold
165
+ * to the cent. A fixed relative allowance like 1e-9 made 1,000,000,000 equal 1,000,000,001.
166
+ */
167
+ const LAST_PLACE_NOISE = 2 * Number.EPSILON;
168
+ function closeEnough(a, b, tolerance) {
169
+ if (a === b)
170
+ return true;
171
+ return Math.abs(a - b) <= tolerance + LAST_PLACE_NOISE * Math.max(Math.abs(a), Math.abs(b));
172
+ }
173
+ function describe(reading) {
174
+ return `${reading.label} is ${JSON.stringify(reading.value)}`;
175
+ }
176
+ export async function evalCompare(session, events, p, diagnose) {
177
+ const [left, right] = await Promise.all([
178
+ readSide(session, events, p.left, diagnose),
179
+ readSide(session, events, p.right, diagnose),
180
+ ]);
181
+ // A side nobody could read (unknown) outranks one that was read and missing: the unreadable one
182
+ // might have been the answer. Otherwise the first side that did not resolve is the failure.
183
+ if ('result' in left || 'result' in right) {
184
+ const results = [left, right].flatMap((r) => ('result' in r ? [r.result] : []));
185
+ return results.find((r) => r.inconclusive !== undefined) ?? results[0] ?? { pass: false };
186
+ }
187
+ const evidence = {
188
+ left: { source: left.label, value: left.value },
189
+ right: { source: right.label, value: right.value },
190
+ };
191
+ if (CompareAs.NUMBER === p.as) {
192
+ const a = numberOf(left.value);
193
+ const b = numberOf(right.value);
194
+ if ('why' in a || 'why' in b) {
195
+ const why = 'why' in a ? `${left.label} ${a.why}` : `${right.label} ${'why' in b ? b.why : ''}`;
196
+ return { pass: false, failureReason: why, inconclusive: why, evidence };
197
+ }
198
+ const tolerance = p.tolerance ?? 0;
199
+ if (closeEnough(a.n, b.n, tolerance))
200
+ return { pass: true, evidence };
201
+ const band = 0 === tolerance ? '' : ` (tolerance ${String(tolerance)})`;
202
+ return {
203
+ pass: false,
204
+ failureReason: `${describe(left)} → ${String(a.n)}, but ${describe(right)} → ${String(b.n)}${band} — they differ`,
205
+ observed: `${String(a.n)} against ${String(b.n)}`,
206
+ expected: `the two numbers to agree${band}`,
207
+ assertion: 'compare.number',
208
+ evidence,
209
+ };
210
+ }
211
+ if (left.value === right.value)
212
+ return { pass: true, evidence };
213
+ const numeric = numberOf(left.value);
214
+ const other = numberOf(right.value);
215
+ const hint = 'n' in numeric && 'n' in other && closeEnough(numeric.n, other.n, 0)
216
+ ? ' — they hold the same number in different forms; compare them with `as: "number"`'
217
+ : '';
218
+ return {
219
+ pass: false,
220
+ failureReason: `${describe(left)}, but ${describe(right)}${hint}`,
221
+ observed: `${JSON.stringify(left.value)} against ${JSON.stringify(right.value)}`,
222
+ expected: 'the two values to be equal',
223
+ assertion: 'compare.value',
224
+ evidence,
225
+ };
226
+ }
@@ -11,4 +11,6 @@ import { type EvalResult } from './predicate-eval.js';
11
11
  import type { PredicateSession } from './predicate-session.js';
12
12
  import { type Baseline, type PropertyAssertion } from './property.js';
13
13
  export declare function evalElement(session: PredicateSession, query: ElementQuery, state: ElementState | undefined, absent: boolean, diagnose: boolean): Promise<EvalResult>;
14
+ /** The text of every element a passing match described, joined — what a reader sees there. */
15
+ export declare function joinedText(evidence: unknown): string;
14
16
  export declare function withTextProperty(base: EvalResult, assertion: PropertyAssertion, subject: string, baseline?: Baseline): EvalResult;
@@ -7,7 +7,7 @@
7
7
  * ever enrich a failure. Nothing else in the predicate layer talks to `ReticleCommand.MATCH`.
8
8
  */
9
9
  import { ReticleCommand, } from '@reticlehq/core';
10
- import { residualQueryChecks, satisfiesResiduals, describeResidual, } from './predicate-eval.js';
10
+ import { describeUnusableElementQuery, residualQueryChecks, satisfiesResiduals, describeResidual, } from './predicate-eval.js';
11
11
  import { describeTestidMiss } from './testid-near-miss.js';
12
12
  import { describeSplitTextMiss } from './split-text-miss.js';
13
13
  import { satisfiesProperty } from './property.js';
@@ -66,16 +66,56 @@ function substantiveMatches(query, elements) {
66
66
  return elements;
67
67
  return elements.filter((e) => e.name.length > 0 || (e.text ?? '').trim().length > 0);
68
68
  }
69
+ /**
70
+ * The first SDK release that can answer each element state added after the vocabulary was first
71
+ * published. A page built before it never finds the name in its state list, so it reports the state
72
+ * as not held, and an `absent` check on it passes whatever the page shows.
73
+ */
74
+ const ELEMENT_STATE_SINCE = {
75
+ // The key is checked against ElementState by the Record type, so a misspelt state cannot compile.
76
+ pressed: '3.4.0',
77
+ };
78
+ /** Leading `major.minor.patch` as numbers; a pre-release of a version counts as that version. */
79
+ function versionParts(version) {
80
+ const m = /^(\d+)\.(\d+)\.(\d+)/.exec(version);
81
+ return null === m ? undefined : [Number(m[1]), Number(m[2]), Number(m[3])];
82
+ }
83
+ /** The state, when the page's SDK is older than the first release that answers it. */
84
+ function stateTheSdkPredates(sdk, state) {
85
+ const since = state === undefined ? undefined : ELEMENT_STATE_SINCE[state];
86
+ if (sdk === undefined || state === undefined || since === undefined)
87
+ return undefined;
88
+ const have = versionParts(sdk);
89
+ const need = versionParts(since);
90
+ if (have === undefined || need === undefined)
91
+ return undefined;
92
+ for (let i = 0; i < 3; i += 1) {
93
+ if (have[i] !== need[i])
94
+ return (have[i] ?? 0) < (need[i] ?? 0) ? { sdk, state, since } : undefined;
95
+ }
96
+ return undefined;
97
+ }
69
98
  export async function evalElement(session, query, state, absent, diagnose) {
99
+ const tooOld = stateTheSdkPredates(session.sdkVersion, state);
100
+ if (tooOld !== undefined) {
101
+ const reason = `the page's SDK is ${tooOld.sdk}, and the '${tooOld.state}' state needs ${tooOld.since} or ` +
102
+ `newer: an older page cannot see it and would report it as not held. Update the page's ` +
103
+ `@reticlehq packages to ${tooOld.since} or newer`;
104
+ return {
105
+ pass: false,
106
+ failureReason: reason,
107
+ inconclusive: reason,
108
+ observed: `SDK ${tooOld.sdk}`,
109
+ expected: `SDK ${tooOld.since} or newer, which can answer '${tooOld.state}'`,
110
+ assertion: 'element.state',
111
+ };
112
+ }
70
113
  // Fields the browser's locator would have DROPPED, enforced back here — see residualQueryChecks.
71
114
  // Checked before the round-trip when nothing can enforce them: a predicate that cannot be evaluated
72
115
  // must say so rather than resolve to whatever the surviving half of it happened to match.
73
116
  const residual = residualQueryChecks(query);
74
117
  if (residual.unusable.length > 0) {
75
- const reason = `the element locator ignores ${residual.unusable.map((f) => `\`${f}\``).join(', ')} ` +
76
- `in ${JSON.stringify(query)} — it resolves by the first of by+value, component/source, role, ` +
77
- 'text, label, placeholder, testid, alt that is present, and nothing here can check the rest. ' +
78
- 'Assert them one locator at a time, or move the extra field into the locator';
118
+ const reason = describeUnusableElementQuery(query, residual.unusable);
79
119
  return { pass: false, failureReason: reason, inconclusive: reason };
80
120
  }
81
121
  let match = await matchOnce(session, query, state);
@@ -227,11 +267,15 @@ export async function evalElement(session, query, state, absent, diagnose) {
227
267
  observed: `no matching element on the page${suffix}`,
228
268
  expected: `an element matching ${subject}${state === undefined ? '' : ` in state '${state}'`}`,
229
269
  assertion: 'element.present',
230
- ...(present.length > 0
270
+ // `splitText` rides on the evidence because it is a POSITIVE observation: the browser found the
271
+ // string in the rendered page. `annotateThrottledMiss` reads it so a miss on a backgrounded tab
272
+ // is not blamed on a render that demonstrably happened.
273
+ ...(present.length > 0 || splitText !== undefined
231
274
  ? {
232
275
  evidence: {
233
- presentTestids: present,
234
- ...(total === undefined ? {} : { presentTestidsTotal: total }),
276
+ ...(present.length > 0 ? { presentTestids: present } : {}),
277
+ ...(total === undefined || 0 === present.length ? {} : { presentTestidsTotal: total }),
278
+ ...(splitText === undefined ? {} : { splitText: match.hint?.splitText }),
235
279
  },
236
280
  }
237
281
  : {}),
@@ -255,11 +299,16 @@ function textOf(element) {
255
299
  const value = element.text;
256
300
  return 'string' === typeof value ? value : '';
257
301
  }
302
+ /** The text of every element a passing match described, joined — what a reader sees there. */
303
+ export function joinedText(evidence) {
304
+ const described = Array.isArray(evidence) ? evidence : [];
305
+ return described.map(textOf).join(' ').trim();
306
+ }
258
307
  export function withTextProperty(base, assertion, subject, baseline) {
259
308
  if (!base.pass)
260
309
  return base;
261
310
  const described = Array.isArray(base.evidence) ? base.evidence : [];
262
- const text = described.map(textOf).join(' ').trim();
311
+ const text = joinedText(described);
263
312
  const result = satisfiesProperty(text, assertion, baseline);
264
313
  // Nothing was compared — a relative property with no before-reading. See the twin in `evalState`.
265
314
  if (true === result.unevaluated) {