@reticlehq/engine 3.3.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.
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) {
@@ -74,8 +74,49 @@ export declare function num(value: unknown): number | undefined;
74
74
  * `{$gte,$lte,$gt,$lt}` (numbers), `{$contains}` (array membership or substring), `{$length}`.
75
75
  */
76
76
  export declare function matchValue(got: unknown, want: unknown): boolean;
77
- /** Shallow JSON pattern match: each key in `pattern` must match (see matchValue). */
77
+ /** One pattern key read out of a payload: its value, or where the walk stopped. */
78
+ export interface FieldReading {
79
+ found: boolean;
80
+ value: unknown;
81
+ /** On a miss, the keys that were there at the deepest level reached. */
82
+ availableKeys?: string[];
83
+ }
84
+ /**
85
+ * Read one pattern key out of a payload.
86
+ *
87
+ * A key the payload holds AS WRITTEN wins, so a literal `"a.b"` key keeps meaning what it always
88
+ * meant. Otherwise a dotted key is a path in the grammar `state.path` already speaks — own keys and
89
+ * canonical array indices, via `selectPath` — because most APIs wrap their answer
90
+ * (`{ data: { status } }`) and a top-level-only match left `bodyContains` as the only reach for a
91
+ * nested field, the substring a key name has already fooled once.
92
+ */
93
+ export declare function readField(actual: Record<string, unknown>, key: string): FieldReading;
94
+ /**
95
+ * JSON pattern match: each key in `pattern` must match (see matchValue).
96
+ *
97
+ * A key is a field name or a dotted path to one (see readField). A nested literal OBJECT is still
98
+ * compared whole, as `equals` is: loosening that would quietly turn every existing exact assertion
99
+ * into a partial one, and the dotted path is the field-by-field form.
100
+ */
78
101
  export declare function dataMatches(actual: Record<string, unknown>, pattern: Record<string, unknown>): boolean;
102
+ /**
103
+ * The first pattern key that did not hold, said the way an agent can act on: what the field held,
104
+ * or that it was missing and which keys were there instead.
105
+ *
106
+ * A whole-object comparison that failed only because the payload carries MORE keys gets told the
107
+ * dotted path that would have matched the one field, because that is the mistake it almost always is.
108
+ */
109
+ export declare function describeFieldMiss(actual: Record<string, unknown>, pattern: Record<string, unknown>): string | undefined;
110
+ /** The same, over a captured body — undefined when the body is not a JSON object. */
111
+ export declare function describeBodyFieldMiss(body: string, pattern: Record<string, unknown>): string | undefined;
112
+ export declare function parseJsonObject(body: string): Record<string, unknown> | undefined;
113
+ /**
114
+ * Did redaction hide this key, at it or at any parent on its path?
115
+ *
116
+ * A parent redacted wholesale (`{ secrets: "[REDACTED]" }`) makes every field under it unreadable,
117
+ * and reporting that as "missing" would blame the server for the observer's own redaction.
118
+ */
119
+ export declare function redactedOnPath(actual: Record<string, unknown>, key: string): boolean;
79
120
  /**
80
121
  * What a field-level clause over a captured body came to.
81
122
  *
@@ -86,7 +127,7 @@ export type BodyFieldVerdict = 'match' | 'mismatch' | {
86
127
  redacted: string;
87
128
  };
88
129
  /**
89
- * Shallow JSON field match over a captured body, for either half of the exchange.
130
+ * JSON field match over a captured body, for either half of the exchange.
90
131
  *
91
132
  * One function because both halves ask the identical question, and the request side already had
92
133
  * this exact sequence written out — parse, reject a non-object, check the wanted keys for
@@ -1,4 +1,4 @@
1
- import { PredicateKind, REDACTED_VALUE } from '@reticlehq/core';
1
+ import { PredicateKind, REDACTED_VALUE, selectPath } from '@reticlehq/core';
2
2
  export function str(value) {
3
3
  return 'string' === typeof value ? value : undefined;
4
4
  }
@@ -96,16 +96,116 @@ function structurallyEqual(got, want) {
96
96
  return false;
97
97
  return keys.every((k) => k in b && structurallyEqual(a[k], b[k]));
98
98
  }
99
- /** Shallow JSON pattern match: each key in `pattern` must match (see matchValue). */
99
+ /**
100
+ * Read one pattern key out of a payload.
101
+ *
102
+ * A key the payload holds AS WRITTEN wins, so a literal `"a.b"` key keeps meaning what it always
103
+ * meant. Otherwise a dotted key is a path in the grammar `state.path` already speaks — own keys and
104
+ * canonical array indices, via `selectPath` — because most APIs wrap their answer
105
+ * (`{ data: { status } }`) and a top-level-only match left `bodyContains` as the only reach for a
106
+ * nested field, the substring a key name has already fooled once.
107
+ */
108
+ export function readField(actual, key) {
109
+ if (Object.hasOwn(actual, key))
110
+ return { found: true, value: actual[key] };
111
+ if (!key.includes('.'))
112
+ return { found: false, value: undefined, availableKeys: Object.keys(actual) };
113
+ const selection = selectPath(actual, key);
114
+ return selection.found
115
+ ? { found: true, value: selection.value }
116
+ : {
117
+ found: false,
118
+ value: undefined,
119
+ ...(selection.availableKeys === undefined
120
+ ? {}
121
+ : { availableKeys: selection.availableKeys }),
122
+ };
123
+ }
124
+ /**
125
+ * JSON pattern match: each key in `pattern` must match (see matchValue).
126
+ *
127
+ * A key is a field name or a dotted path to one (see readField). A nested literal OBJECT is still
128
+ * compared whole, as `equals` is: loosening that would quietly turn every existing exact assertion
129
+ * into a partial one, and the dotted path is the field-by-field form.
130
+ */
100
131
  export function dataMatches(actual, pattern) {
101
132
  for (const [key, want] of Object.entries(pattern)) {
102
- if (!matchValue(actual[key], want))
133
+ if (!matchValue(readField(actual, key).value, want))
103
134
  return false;
104
135
  }
105
136
  return true;
106
137
  }
107
138
  /**
108
- * Shallow JSON field match over a captured body, for either half of the exchange.
139
+ * The first pattern key that did not hold, said the way an agent can act on: what the field held,
140
+ * or that it was missing and which keys were there instead.
141
+ *
142
+ * A whole-object comparison that failed only because the payload carries MORE keys gets told the
143
+ * dotted path that would have matched the one field, because that is the mistake it almost always is.
144
+ */
145
+ export function describeFieldMiss(actual, pattern) {
146
+ for (const [key, want] of Object.entries(pattern)) {
147
+ const reading = readField(actual, key);
148
+ if (matchValue(reading.value, want))
149
+ continue;
150
+ if (!reading.found) {
151
+ const keys = reading.availableKeys ?? [];
152
+ return `${JSON.stringify(key)} is missing${0 === keys.length ? '' : ` (keys there: ${keys.join(', ')})`}`;
153
+ }
154
+ const held = `${JSON.stringify(key)} is ${JSON.stringify(reading.value)}`;
155
+ const firstNested = nestedLiteralKey(want);
156
+ return firstNested === undefined
157
+ ? held
158
+ : `${held} — a nested object is compared WHOLE; to match one field, key it by its path: ${JSON.stringify(`${key}.${firstNested}`)}`;
159
+ }
160
+ return undefined;
161
+ }
162
+ /** The first key of a nested literal object pattern, or undefined for anything else. */
163
+ function nestedLiteralKey(want) {
164
+ if ('object' !== typeof want || null === want || Array.isArray(want))
165
+ return undefined;
166
+ const keys = Object.keys(want);
167
+ if (keys.some((k) => k.startsWith('$')))
168
+ return undefined;
169
+ return keys[0];
170
+ }
171
+ /** The same, over a captured body — undefined when the body is not a JSON object. */
172
+ export function describeBodyFieldMiss(body, pattern) {
173
+ const actual = parseJsonObject(body);
174
+ return actual === undefined ? undefined : describeFieldMiss(actual, pattern);
175
+ }
176
+ export function parseJsonObject(body) {
177
+ let payload;
178
+ try {
179
+ payload = JSON.parse(body);
180
+ }
181
+ catch {
182
+ return undefined;
183
+ }
184
+ if (null === payload || 'object' !== typeof payload || Array.isArray(payload))
185
+ return undefined;
186
+ return payload;
187
+ }
188
+ /**
189
+ * Did redaction hide this key, at it or at any parent on its path?
190
+ *
191
+ * A parent redacted wholesale (`{ secrets: "[REDACTED]" }`) makes every field under it unreadable,
192
+ * and reporting that as "missing" would blame the server for the observer's own redaction.
193
+ */
194
+ export function redactedOnPath(actual, key) {
195
+ if (Object.hasOwn(actual, key))
196
+ return REDACTED_VALUE === actual[key];
197
+ const segments = key.split('.');
198
+ for (let i = 1; i <= segments.length; i += 1) {
199
+ const prefix = selectPath(actual, segments.slice(0, i).join('.'));
200
+ if (!prefix.found)
201
+ return false;
202
+ if (REDACTED_VALUE === prefix.value)
203
+ return true;
204
+ }
205
+ return false;
206
+ }
207
+ /**
208
+ * JSON field match over a captured body, for either half of the exchange.
109
209
  *
110
210
  * One function because both halves ask the identical question, and the request side already had
111
211
  * this exact sequence written out — parse, reject a non-object, check the wanted keys for
@@ -116,17 +216,10 @@ export function dataMatches(actual, pattern) {
116
216
  * exist for those bodies.
117
217
  */
118
218
  export function matchJsonBody(body, pattern) {
119
- let payload;
120
- try {
121
- payload = JSON.parse(body);
122
- }
123
- catch {
124
- return 'mismatch';
125
- }
126
- if (null === payload || 'object' !== typeof payload || Array.isArray(payload))
219
+ const actual = parseJsonObject(body);
220
+ if (actual === undefined)
127
221
  return 'mismatch';
128
- const actual = payload;
129
- const redacted = Object.keys(pattern).find((key) => REDACTED_VALUE === actual[key]);
222
+ const redacted = Object.keys(pattern).find((key) => redactedOnPath(actual, key));
130
223
  if (redacted !== undefined)
131
224
  return { redacted };
132
225
  return dataMatches(actual, pattern) ? 'match' : 'mismatch';
@@ -3,7 +3,7 @@ import { describeObserved } from './observed-in-window.js';
3
3
  import { netEvidence } from './net-evidence.js';
4
4
  import { checkRequestBody, newRequestBodyState, requestBodyVerdict, } from './predicate-request-body.js';
5
5
  export { evalConsole } from './predicate-console.js';
6
- import { clipBody, dataMatches, describeNetFilter, matchJsonBody, num, str, } from './predicate-eval-kit.js';
6
+ import { clipBody, dataMatches, describeBodyFieldMiss, describeFieldMiss, describeNetFilter, matchJsonBody, num, redactedOnPath, str, } from './predicate-eval-kit.js';
7
7
  import { keyFragmentOnly } from './body-key-fragment.js';
8
8
  export { clipBody, dataMatches, describeNetFilter, matchValue, str, } from './predicate-eval-kit.js';
9
9
  // The predicate SHAPE — the discriminated union, its aliases and its zod schema — lives in
@@ -464,11 +464,14 @@ export function evalNet(events, p) {
464
464
  }
465
465
  if (bodyMismatch !== undefined && 0 === matches.length) {
466
466
  // The call is there and its body is there; only the VALUE differs. Counting it as zero matches
467
- // points at the wiring, which is the one place the defect is not.
467
+ // points at the wiring, which is the one place the defect is not. A field clause also names the
468
+ // field that differed, because a 200-character clip may not reach it.
469
+ const field = p.bodyMatches === undefined ? undefined : describeBodyFieldMiss(bodyMismatch, p.bodyMatches);
470
+ const because = field === undefined ? '' : `: ${field}`;
468
471
  return {
469
472
  pass: false,
470
- failureReason: `a call matching ${describeNetFilter(p)} was made and answered ${JSON.stringify(clipBody(bodyMismatch))}, which does not carry ${wantedBody(p)} — the request fired, the response value is what differed`,
471
- observed: `response body ${JSON.stringify(clipBody(bodyMismatch))}`,
473
+ failureReason: `a call matching ${describeNetFilter(p)} was made and answered ${JSON.stringify(clipBody(bodyMismatch))}, which does not carry ${wantedBody(p)}${because} — the request fired, the response value is what differed`,
474
+ observed: `response body ${JSON.stringify(clipBody(bodyMismatch))}${because}`,
472
475
  expected: `a response body carrying ${wantedBody(p)}`,
473
476
  assertion: 'net.bodyContains',
474
477
  };
@@ -559,6 +562,12 @@ export function evalAnimation(events, p) {
559
562
  };
560
563
  }
561
564
  export function evalSignal(events, p) {
565
+ /**
566
+ * A pattern key the transport sanitizer redacted on a payload of the right name. The marker is
567
+ * written for a sensitive key whatever it held, so neither `*` nor a value can be judged against it
568
+ * — the same rule the body clauses keep.
569
+ */
570
+ let redactedField;
562
571
  const isMatch = (e) => {
563
572
  if (e.type !== EventType.SIGNAL)
564
573
  return false;
@@ -566,19 +575,43 @@ export function evalSignal(events, p) {
566
575
  return false;
567
576
  if (p.dataMatches !== undefined) {
568
577
  const payload = (e.data['data'] ?? {});
578
+ const hidden = 'object' === typeof payload
579
+ ? Object.keys(p.dataMatches).find((key) => redactedOnPath(payload, key))
580
+ : undefined;
581
+ if (hidden !== undefined) {
582
+ redactedField ??= hidden;
583
+ return false;
584
+ }
569
585
  if (!dataMatches(payload, p.dataMatches))
570
586
  return false;
571
587
  }
572
588
  return true;
573
589
  };
590
+ const redactedVerdict = () => {
591
+ if (redactedField === undefined)
592
+ return undefined;
593
+ const field = JSON.stringify(redactedField);
594
+ return {
595
+ pass: false,
596
+ inconclusive: `signal '${p.name ?? '(any)'}' fired, but its ${field} was REDACTED before it was recorded, so this clause cannot be judged — a redacted field is unknown, not different. Assert on a non-sensitive key, or on the effect the value had`,
597
+ observed: `a signal payload whose ${field} is ${REDACTED_VALUE}`,
598
+ expected: `signal '${p.name ?? '(any)'}' with payload matching ${JSON.stringify(p.dataMatches)}`,
599
+ assertion: 'signal.payload',
600
+ };
601
+ };
574
602
  // `count` (exact) turns presence into a cardinality assertion, exactly as it does on `net`. The
575
603
  // double-fire is invisible to every state-only oracle — a handler wired twice leaves the store in
576
604
  // the right shape and fires the signal twice — and so is the wrong-name fire, where the intended
577
605
  // signal fires once beside a mistyped sibling and a presence check cannot say which is which.
578
606
  // Counting only what the MATCHER matched is what separates them. Omit = presence (≥1).
579
607
  if (p.count !== undefined) {
608
+ const matched = events.filter(isMatch).length;
609
+ // A redacted payload might have been one of the matches, so no count over it is decided.
610
+ const unjudgeable = redactedVerdict();
611
+ if (unjudgeable !== undefined)
612
+ return unjudgeable;
580
613
  return evalExactCount({
581
- matched: events.filter(isMatch).length,
614
+ matched,
582
615
  want: p.count,
583
616
  noun: 'signal(s)',
584
617
  filter: describeSignalFilter(p),
@@ -588,17 +621,25 @@ export function evalSignal(events, p) {
588
621
  const hit = events.find(isMatch);
589
622
  if (hit !== undefined)
590
623
  return { pass: true, evidence: hit.data };
624
+ // `find` scanned every event to get here, so a redacted payload has been seen if there was one.
625
+ const unjudgeable = redactedVerdict();
626
+ if (unjudgeable !== undefined)
627
+ return unjudgeable;
591
628
  // Near-miss: show signals that fired with the same name (so the agent sees the real data).
592
629
  const sameName = events
593
630
  .filter((e) => e.type === EventType.SIGNAL && (p.name === undefined || str(e.data['name']) === p.name))
594
631
  .map((e) => e.data['data'] ?? e.data);
632
+ const first = sameName[0];
633
+ const fieldMiss = p.dataMatches !== undefined && 'object' === typeof first && first !== null
634
+ ? describeFieldMiss(first, p.dataMatches)
635
+ : undefined;
595
636
  return {
596
637
  pass: false,
597
638
  failureReason: sameName.length > 0
598
639
  ? `signal '${p.name ?? '(any)'}' fired ${String(sameName.length)}x but data didn't match`
599
640
  : `no signal matched ${JSON.stringify(p)}`,
600
641
  observed: sameName.length > 0
601
- ? `signal '${p.name ?? '(any)'}' fired ${String(sameName.length)}x, payload: ${JSON.stringify(sameName[0])}`
642
+ ? `signal '${p.name ?? '(any)'}' fired ${String(sameName.length)}x, payload: ${JSON.stringify(first)}${fieldMiss === undefined ? '' : `; ${fieldMiss}`}`
602
643
  : // Name what DID fire: a typo'd signal name and a genuinely dead action produce the same
603
644
  // sentence otherwise, and the agent cannot tell them apart. See observed-in-window.ts.
604
645
  `signal '${p.name ?? '(any)'}' never fired; ${describeObserved('signals', events.filter((e) => e.type === EventType.SIGNAL).map((e) => str(e.data['name']) ?? ''))}`,
@@ -34,6 +34,7 @@ const EXAMPLES = {
34
34
  [PredicateKind.SIGNAL]: '{ kind: "signal", name: "todos:loaded" }',
35
35
  [PredicateKind.STATE]: '{ kind: "state", path: "cart.total", equals: 0 }',
36
36
  [PredicateKind.SETTLED]: '{ kind: "settled" }',
37
+ [PredicateKind.COMPARE]: '{ kind: "compare", left: { from: "text", scope: "#total" }, right: { from: "net", urlContains: "/api/cart", path: "total" }, as: "number" }',
37
38
  [PredicateKind.ALL_OF]: '{ kind: "allOf", predicates: [{ kind: "text", contains: "Saved" }, { kind: "console", level: "error", absent: true }] }',
38
39
  [PredicateKind.ANY_OF]: '{ kind: "anyOf", predicates: [{ kind: "text", contains: "Saved" }, { kind: "text", contains: "Updated" }] }',
39
40
  [PredicateKind.NOT]: '{ kind: "not", predicate: { kind: "text", contains: "Error" } }',
@@ -16,7 +16,7 @@
16
16
  * nothing to report." This is that, applied one step earlier.
17
17
  */
18
18
  import { PredicateKind } from '@reticlehq/core';
19
- import { residualQueryChecks } from './predicate-schema.js';
19
+ import { describeUnusableElementQuery, residualQueryChecks } from './predicate-schema.js';
20
20
  /** Composite predicates nest; the unusable one can be at any depth. */
21
21
  const NESTED_KEYS = ['predicates', 'predicate'];
22
22
  const isRecord = (v) => 'object' === typeof v && null !== v;
@@ -48,10 +48,8 @@ export function unevaluablePredicateReason(predicate) {
48
48
  const residual = residualQueryChecks(query);
49
49
  if (0 === residual.unusable.length)
50
50
  continue;
51
- return (`the element locator ignores ${residual.unusable.map((f) => `\`${f}\``).join(', ')} ` +
52
- `in ${JSON.stringify(query)} — it resolves by the first of by+value, component/source, role, ` +
53
- 'text, label, placeholder, testid, alt that is present, and nothing here can check the rest. ' +
54
- 'Assert them one locator at a time, or move the extra field into the locator. ' +
51
+ return (describeUnusableElementQuery(query, residual.unusable) +
52
+ ' ' +
55
53
  'Nothing was acted on: this predicate could never have been evaluated, so refusing it costs ' +
56
54
  'you nothing and spending the action on it would have cost you the verdict.');
57
55
  }
@@ -14,7 +14,7 @@
14
14
  * Extracted from `predicate-eval.ts`, which was at the 1000-line cap.
15
15
  */
16
16
  import { REDACTED_VALUE } from '@reticlehq/core';
17
- import { clipBody, describeNetFilter, matchJsonBody, str, } from './predicate-eval-kit.js';
17
+ import { clipBody, describeBodyFieldMiss, describeNetFilter, matchJsonBody, str, } from './predicate-eval-kit.js';
18
18
  export function newRequestBodyState() {
19
19
  return { unrecorded: false };
20
20
  }
@@ -99,10 +99,14 @@ export function requestBodyVerdict(state, predicate, matchCount) {
99
99
  // Named separately from "no call matched", for the reason the response side already learned: the
100
100
  // request DID fire, and reporting zero matches sends the caller to check the url and the method,
101
101
  // which are both fine, instead of to the value the UI actually sent.
102
+ const field = predicate.requestBodyMatches === undefined
103
+ ? undefined
104
+ : describeBodyFieldMiss(state.mismatch, predicate.requestBodyMatches);
105
+ const because = field === undefined ? '' : `: ${field}`;
102
106
  return {
103
107
  pass: false,
104
- failureReason: `a call matching ${describeNetFilter(predicate)} was sent with ${JSON.stringify(clipBody(state.mismatch))}, which does not match the request-body clause — the request fired, the payload is what differed`,
105
- observed: `request body ${JSON.stringify(clipBody(state.mismatch))}`,
108
+ failureReason: `a call matching ${describeNetFilter(predicate)} was sent with ${JSON.stringify(clipBody(state.mismatch))}, which does not match the request-body clause${because} — the request fired, the payload is what differed`,
109
+ observed: `request body ${JSON.stringify(clipBody(state.mismatch))}${because}`,
106
110
  expected: `a request body matching ${wanted}`,
107
111
  assertion: 'net.requestBody',
108
112
  };
@@ -26,6 +26,8 @@ interface ResidualQueryChecks {
26
26
  * outcome the caller was already assuming.
27
27
  */
28
28
  export declare function residualQueryChecks(query: ElementQuery): ResidualQueryChecks;
29
+ /** Explain an element query whose locator drops fields it cannot verify. */
30
+ export declare function describeUnusableElementQuery(query: ElementQuery, unusable: readonly string[]): string;
29
31
  /** Does this element satisfy every field the locator dropped? */
30
32
  export declare function satisfiesResiduals(element: ElementDescriptor, checks: readonly [string, string][]): boolean;
31
33
  /** How the element's own reading of a dropped field should be REPORTED back on a failure. */
@@ -112,6 +112,18 @@ export function residualQueryChecks(query) {
112
112
  }
113
113
  return { checks, unusable };
114
114
  }
115
+ /** Explain an element query whose locator drops fields it cannot verify. */
116
+ export function describeUnusableElementQuery(query, unusable) {
117
+ const preservedChecks = Object.fromEntries(residualQueryChecks(query).checks);
118
+ const roleAlternatives = QueryBy.ROLE === query.by && query.value === undefined && query.role !== undefined
119
+ ? ` For this role locator, use ${JSON.stringify({ by: QueryBy.ROLE, value: query.role, ...(query.name === undefined ? {} : { name: query.name }), ...preservedChecks })} or ${JSON.stringify({ role: query.role, ...(query.name === undefined ? {} : { name: query.name }), ...preservedChecks })}.`
120
+ : '';
121
+ return (`the element locator ignores ${unusable.map((field) => `\`${field}\``).join(', ')} ` +
122
+ `in ${JSON.stringify(query)} — it resolves by the first of by+value, component/source, role, ` +
123
+ 'text, label, placeholder, testid, alt that is present, and nothing here can check the rest.' +
124
+ roleAlternatives +
125
+ ' Assert them one locator at a time, or move the extra field into the locator.');
126
+ }
115
127
  /** Does this element satisfy every field the locator dropped? */
116
128
  export function satisfiesResiduals(element, checks) {
117
129
  return checks.every(([field, want]) => true === RESIDUAL_CHECKS[field]?.(element, want));
@@ -209,6 +221,12 @@ export function nestedKeysOf(schema) {
209
221
  // `instanceof z.ZodObject` narrows to ZodObject<any>, whose `.shape` is `any`. Name the shape
210
222
  // type so the keys are read off something typed rather than laundering an `any` through
211
223
  // Object.keys.
224
+ // A union of objects (`compare`'s `left`/`right`) lists every option's keys: which ones apply is
225
+ // decided by the discriminator, and the rejection already names that.
226
+ if (inner instanceof z.ZodDiscriminatedUnion) {
227
+ const options = inner.options;
228
+ return [...new Set(options.flatMap((option) => nestedKeysOf(option)))];
229
+ }
212
230
  if (!(inner instanceof z.ZodObject))
213
231
  return [];
214
232
  return Object.keys(inner.shape);
@@ -16,6 +16,11 @@ export interface PredicateSession {
16
16
  onEvent(listener: (event: ReticleEvent) => void): () => void;
17
17
  /** Milliseconds since connect — the same clock that stamps event `t` (injected, testable). */
18
18
  elapsed(): number;
19
+ /**
20
+ * The page SDK's package version from its hello, when it sent one. Read to refuse an element
21
+ * state the page is too old to answer (see ELEMENT_STATE_SINCE). Undefined for a hand-wired page.
22
+ */
23
+ sdkVersion?: string | undefined;
19
24
  /**
20
25
  * Where the app is RIGHT NOW — the session's live URL, kept current across SPA navigation.
21
26
  *
@@ -1,4 +1,4 @@
1
- import { ConsequenceKind, PredicateKind } from '@reticlehq/core';
1
+ import { ConsequenceKind, PredicateKind, compareSourceClauses } from '@reticlehq/core';
2
2
  /**
3
3
  * Convert a mustHold predicate into the ordered ExpectedLinks the divergence capsule walks. Only the
4
4
  * consequence kinds (signal/net/state) become links — a presence check (element/text) can't diverge in a
@@ -32,6 +32,8 @@ export function predicateToExpectedLinks(predicate) {
32
32
  case PredicateKind.ALL_OF:
33
33
  case PredicateKind.ANY_OF:
34
34
  return predicate.predicates.flatMap(predicateToExpectedLinks);
35
+ case PredicateKind.COMPARE:
36
+ return compareSourceClauses(predicate).flatMap(predicateToExpectedLinks);
35
37
  default:
36
38
  return [];
37
39
  }
@@ -5,6 +5,7 @@ import { evalRoute } from './predicate-route.js';
5
5
  import { describeSuperseded } from './observed-in-window.js';
6
6
  import { evalElement, withTextProperty } from './predicate-element.js';
7
7
  import { evalState } from './predicate-state.js';
8
+ import { evalCompare } from './predicate-compare.js';
8
9
  import { PredicateSchema, evalNet, evalConsole, evalAnimation, evalSignal, evalSettled, } from './predicate-eval.js';
9
10
  export { PredicateSchema, PredicateKind };
10
11
  import { withinBudget } from './predicate-session.js';
@@ -70,8 +71,23 @@ function annotateThrottledMiss(session, predicate, result) {
70
71
  return result;
71
72
  if (failureRestsOnSeeing(predicate))
72
73
  return result;
74
+ if (foundTextSplitAcrossChildren(result))
75
+ return result;
73
76
  return { ...result, inconclusive: THROTTLED_STARVED_NOTE };
74
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
+ }
75
91
  /**
76
92
  * Has this predicate's failure ALREADY been adjudicated, one level down?
77
93
  *
@@ -258,6 +274,8 @@ diagnose = true, baselines) {
258
274
  const settleEvents = counts === undefined ? events : events.filter((e) => !isAmbient(counts, ambientKeyOf(e)));
259
275
  return evalSettled(settleEvents, predicate, session.elapsed());
260
276
  }
277
+ case PredicateKind.COMPARE:
278
+ return evalCompare(session, events, predicate, diagnose);
261
279
  case PredicateKind.ALL_OF: {
262
280
  const results = clearStarvedWhenSiblingsSaw(predicate.predicates, await Promise.all(predicate.predicates.map((p) => evaluatePredicate(session, p, since, diagnose, baselines))));
263
281
  // A clause that genuinely failed OUTRANKS one nobody could read. Softening a real failure to
@@ -266,13 +284,14 @@ diagnose = true, baselines) {
266
284
  // that was happening.
267
285
  const failed = results.find((r) => !r.pass && r.inconclusive === undefined);
268
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);
269
291
  return {
270
292
  pass: false,
271
293
  failureReason: failed.failureReason ?? 'a sub-predicate of allOf failed',
272
- // A conjunction is decided as soon as ONE clause is: nothing the others do later can
273
- // rescue it. This is what makes the early exit reach real calls, since an exact count is
274
- // usually asserted alongside the UI change it is meant to accompany.
275
- ...(true === failed.decided ? { decided: true } : {}),
294
+ ...(anyDecided ? { decided: true } : {}),
276
295
  evidence: results,
277
296
  };
278
297
  }
@@ -291,7 +310,16 @@ diagnose = true, baselines) {
291
310
  const unreadable = results.find((r) => r.inconclusive !== undefined);
292
311
  if (unreadable !== undefined)
293
312
  return unreadableComposite(unreadable, results);
294
- 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
+ };
295
323
  }
296
324
  case PredicateKind.NOT: {
297
325
  const inner = await evaluatePredicate(session, predicate.predicate, since, diagnose, baselines);
@@ -321,7 +349,8 @@ const POLL_INTERVAL_MS = 150;
321
349
  * poll cadence, large enough to collapse a per-frame event storm into a bounded recheck rate. */
322
350
  const MIN_RECHECK_GAP_MS = 25;
323
351
  /**
324
- * 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.
325
354
  *
326
355
  * A count only rises while a window is open, so "exactly N" is a statement about the END of one and
327
356
  * cannot be settled early — yet every wait here resolves the moment a check passes. Live, on a real
@@ -358,6 +387,22 @@ function assertsExactCount(predicate) {
358
387
  return ((PredicateKind.NET === predicate.kind || PredicateKind.SIGNAL === predicate.kind) &&
359
388
  predicate.count !== undefined);
360
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
+ }
361
406
  /**
362
407
  * Evaluate now, else wait for it to become true (on each event + a poll) until timeout. `since` is
363
408
  * the event-time floor (see evaluatePredicate) so a waiter cannot resolve on a stale buffered event.
@@ -385,8 +430,9 @@ baselines) {
385
430
  let cooldownTimer;
386
431
  /** One-shot re-check timed to when a time-based predicate could first pass. See retryAfterMs. */
387
432
  let hintTimer;
388
- // An exact-count wait keeps watching after it first reads true — see COUNT_CONFIRM_MS.
389
- 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);
390
436
  let confirming = false;
391
437
  let confirmTimer;
392
438
  /** Report a wait that could not run, and END it — see guardedCheck. */
@@ -551,6 +597,13 @@ baselines) {
551
597
  const timer = setTimeout(() => {
552
598
  void evaluatePredicate(reader, predicate, since, true, baselines)
553
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
+ }
554
607
  // Spread the near-miss, do NOT hand-copy two fields. The oracle computes observed / expected
555
608
  // / assertion — the structured cause the repair literature ranks above prose — and the old
556
609
  // `{ pass, evidence, failureReason }` construction DISCARDED them on every timed-out wait and
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@reticlehq/engine",
3
- "version": "3.3.0",
3
+ "version": "3.4.0",
4
4
  "description": "The rules that decide a verdict: read what happened in a running app and say whether the declared consequence held. No browser, no daemon, no command line - an implementation of the OpenVerification specification you can use on its own.",
5
5
  "keywords": [
6
6
  "verification",
@@ -49,17 +49,16 @@
49
49
  },
50
50
  "files": [
51
51
  "dist",
52
- "README.md"
52
+ "README.md",
53
+ "NOTICE"
53
54
  ],
54
55
  "publishConfig": {
55
56
  "access": "public"
56
57
  },
57
58
  "dependencies": {
58
59
  "zod": "^3.24.1",
59
- "@reticlehq/core": "3.3.0"
60
- },
61
- "devDependencies": {
62
- "open-verification": "1.0.0"
60
+ "open-verification": "1.0.0",
61
+ "@reticlehq/core": "3.4.0"
63
62
  },
64
63
  "scripts": {
65
64
  "build": "tsc -b && node ../scripts/alias-dist.mjs",