@reticlehq/engine 3.2.0 → 3.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/NOTICE +5 -0
  2. package/dist/disagreement/body-failures.js +32 -12
  3. package/dist/disagreement/contradiction-evidence.d.ts +1 -1
  4. package/dist/disagreement/contradiction-evidence.js +3 -3
  5. package/dist/disagreement/contradiction-types.d.ts +6 -0
  6. package/dist/disagreement/contradictions.js +24 -30
  7. package/dist/disagreement/echo-mismatch.js +16 -0
  8. package/dist/evidence/already-true.js +14 -3
  9. package/dist/evidence/baseline.d.ts +21 -0
  10. package/dist/evidence/baseline.js +129 -0
  11. package/dist/evidence/instrumentation-gaps.js +8 -2
  12. package/dist/evidence/unsettled.js +7 -1
  13. package/dist/evidence/verified.d.ts +7 -0
  14. package/dist/evidence/verified.js +35 -1
  15. package/dist/question/declared.js +11 -2
  16. package/dist/question/lineage.d.ts +14 -5
  17. package/dist/question/lineage.js +65 -10
  18. package/dist/question/predicate/predicate-asks.js +7 -1
  19. package/dist/question/predicate/predicate-compare.d.ts +18 -0
  20. package/dist/question/predicate/predicate-compare.js +226 -0
  21. package/dist/question/predicate/predicate-element.d.ts +5 -2
  22. package/dist/question/predicate/predicate-element.js +122 -8
  23. package/dist/question/predicate/predicate-eval-kit.d.ts +43 -2
  24. package/dist/question/predicate/predicate-eval-kit.js +107 -14
  25. package/dist/question/predicate/predicate-eval.d.ts +6 -0
  26. package/dist/question/predicate/predicate-eval.js +60 -13
  27. package/dist/question/predicate/predicate-parse.js +1 -0
  28. package/dist/question/predicate/predicate-precheck.js +3 -5
  29. package/dist/question/predicate/predicate-request-body.d.ts +1 -1
  30. package/dist/question/predicate/predicate-request-body.js +7 -3
  31. package/dist/question/predicate/predicate-route.d.ts +2 -1
  32. package/dist/question/predicate/predicate-schema.d.ts +14 -93
  33. package/dist/question/predicate/predicate-schema.js +33 -288
  34. package/dist/question/predicate/predicate-session.d.ts +20 -1
  35. package/dist/question/predicate/predicate-session.js +25 -1
  36. package/dist/question/predicate/predicate-state.d.ts +15 -0
  37. package/dist/question/predicate/predicate-state.js +317 -0
  38. package/dist/question/predicate/predicate-to-links.js +3 -1
  39. package/dist/question/predicate/predicate.d.ts +17 -3
  40. package/dist/question/predicate/predicate.js +200 -336
  41. package/dist/question/predicate/property.d.ts +24 -73
  42. package/dist/question/predicate/property.js +134 -20
  43. package/dist/window/json-salvage.d.ts +2 -1
  44. package/dist/window/json-salvage.js +2 -1
  45. package/package.json +5 -6
@@ -16,6 +16,14 @@
16
16
  * one thing a correlation cannot justify;
17
17
  * - no candidate says the value was not seen to pass through one, and reaches for nothing.
18
18
  *
19
+ * One more source, read rather than recomputed: the SDK stamps `actionId` + `attribution` onto every
20
+ * event observed while a driven action is active (see `core/messages.ts`). That is a time-window
21
+ * heuristic too — `EventAttribution.WINDOW`'s own comment says so — but it is the same tier, already
22
+ * computed, already labelled, and narrower than a fresh look-back, so the join reads it two ways:
23
+ * a candidate stamped with a DIFFERENT act is not a candidate for this one (the stamp rules out; it
24
+ * never rules in), and a stamped change with no signal behind it names the act rather than calling
25
+ * its cause "not in evidence" when the evidence is on the event (#939).
26
+ *
19
27
  * Read-only. Produces no verdict, is not reachable from an assert path, and changes nothing.
20
28
  */
21
29
  import { EventType } from '@reticlehq/core';
@@ -41,9 +49,39 @@ function stateChangesFor(events, query) {
41
49
  return String(e.data['value']) === query.value;
42
50
  });
43
51
  }
44
- /** Events of one kind inside the causal window before `t`, oldest first. */
45
- function precursors(events, type, t) {
46
- return events.filter((e) => e.type === type && e.t < t && e.t >= t - CAUSE_WINDOW_MS);
52
+ /**
53
+ * Events of one kind inside the causal window before `t`, oldest first.
54
+ *
55
+ * When the change being traced carries an `actionId`, a candidate stamped with a DIFFERENT one is
56
+ * dropped: the SDK observed it under another driven action, and five seconds spans several of
57
+ * those. An UNSTAMPED candidate stays. A request fired just before dispatch carries no stamp and its
58
+ * response can still land inside the act — the stamp proves an event belongs elsewhere, it cannot
59
+ * prove an unstamped one is unrelated. Rules out, never rules in.
60
+ */
61
+ function precursors(events, type, t, actionId) {
62
+ return events.filter((e) => e.type === type &&
63
+ e.t < t &&
64
+ e.t >= t - CAUSE_WINDOW_MS &&
65
+ (actionId === undefined || e.actionId === undefined || e.actionId === actionId));
66
+ }
67
+ /**
68
+ * The link from a stamped change to the act that was active when it was observed.
69
+ *
70
+ * Rendered from the tier the event carries, not asserted: `attribution` is present iff `actionId`
71
+ * is, and today there is one tier. It is not an observation — the SDK stamped an id across a span
72
+ * of time — and the text says what that span is, so a reader who acts on the arrow has been told
73
+ * what the arrow is worth.
74
+ */
75
+ function actLink(actionId, attribution) {
76
+ // Rendered from the tier the EVENT carries, never from a constant of our own. The schema says
77
+ // `attribution` is present iff `actionId` is, so on this path it always is; the guard against
78
+ // its absence exists so a contract slip renders a shorter sentence rather than a wrong one.
79
+ const tier = attribution === undefined ? '' : ` — ${attribution} tier`;
80
+ return {
81
+ kind: 'act',
82
+ text: `← attributed to action ${actionId}${tier}: the SDK stamped this action's id on every event between its dispatch and settle. A time window, not dataflow.`,
83
+ observed: false,
84
+ };
47
85
  }
48
86
  /**
49
87
  * Render an inferred link, hedged according to how many things could explain it.
@@ -97,19 +135,36 @@ export function traceLineage(events, query) {
97
135
  observed: true,
98
136
  },
99
137
  ];
100
- const signals = precursors(events, EventType.SIGNAL, latest.t);
138
+ const actionId = latest.actionId;
139
+ const signals = precursors(events, EventType.SIGNAL, latest.t, actionId);
101
140
  if (0 === signals.length) {
102
- return {
103
- found: true,
104
- chain,
105
- note: 'No signal fired in the window before this change, so the value was not seen to pass through one. Nothing further is claimed — the change is real, its cause is not in evidence.',
106
- };
141
+ if (actionId === undefined) {
142
+ return {
143
+ found: true,
144
+ chain,
145
+ note: 'No signal fired in the window before this change, so the value was not seen to pass through one. Nothing further is claimed — the change is real, its cause is not in evidence.',
146
+ };
147
+ }
148
+ // The common case: `reticle.signal()` is a call the APP must make, and most apps never do. But
149
+ // this change was observed under a driven action, and that is on the event. Saying its cause is
150
+ // "not in evidence" would be a factual claim, and a false one.
151
+ chain.push(actLink(actionId, latest.attribution));
152
+ const driven = precursors(events, EventType.NET_REQUEST, latest.t, actionId);
153
+ if (0 === driven.length) {
154
+ return {
155
+ found: true,
156
+ chain,
157
+ note: 'No signal fired, and no request in the window carries this action or none at all, so the chain stops at the act rather than joining across a gap in the evidence.',
158
+ };
159
+ }
160
+ chain.push(inferredLink('net', driven.map(netLabel)));
161
+ return { found: true, chain };
107
162
  }
108
163
  chain.push(inferredLink('signal', signals.map(signalLabel)));
109
164
  // Anchored on the OLDEST candidate signal: a request that preceded any of them could have produced
110
165
  // it, and narrowing to the newest would quietly discard candidates for the link below.
111
166
  const anchor = signals[0]?.t ?? latest.t;
112
- const calls = precursors(events, EventType.NET_REQUEST, anchor);
167
+ const calls = precursors(events, EventType.NET_REQUEST, anchor, actionId);
113
168
  if (0 === calls.length) {
114
169
  return {
115
170
  found: true,
@@ -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
+ }
@@ -6,8 +6,11 @@
6
6
  * back (`residualQueryChecks`), the absent/present asymmetry, and the near-miss diagnostics that only
7
7
  * ever enrich a failure. Nothing else in the predicate layer talks to `ReticleCommand.MATCH`.
8
8
  */
9
- import { type ElementQuery, type ElementState, type MatchResult } from '@reticlehq/core';
9
+ import { type ElementQuery, type ElementState } from '@reticlehq/core';
10
10
  import { type EvalResult } from './predicate-eval.js';
11
11
  import type { PredicateSession } from './predicate-session.js';
12
- export declare function matchOnce(session: PredicateSession, query: ElementQuery, state: ElementState | undefined): Promise<MatchResult>;
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;
16
+ export declare function withTextProperty(base: EvalResult, assertion: PropertyAssertion, subject: string, baseline?: Baseline): EvalResult;
@@ -7,10 +7,23 @@
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
- export async function matchOnce(session, query, state) {
13
+ import { satisfiesProperty } from './property.js';
14
+ /**
15
+ * The caveat for a present-testid list that was cut at its cap, or nothing when it was whole.
16
+ *
17
+ * Phrased as what the list IS — "the first N of M in document order" — rather than as an apology,
18
+ * because the agent's next move depends on knowing the shape: a region absent from a capped list is
19
+ * unexamined, not absent. Empty when nothing was cut, so an ordinary miss keeps the message it had.
20
+ */
21
+ function describePresentTestidsCut(shown, total) {
22
+ if (total === undefined || total <= shown)
23
+ return '';
24
+ return ` (the present-testid list shows the first ${String(shown)} of ${String(total)} in document order — absence from it proves nothing)`;
25
+ }
26
+ async function matchOnce(session, query, state) {
14
27
  const res = await session.command(ReticleCommand.MATCH, { query, state });
15
28
  if (!res.ok)
16
29
  return { matched: false, count: 0, elements: [] };
@@ -53,16 +66,56 @@ function substantiveMatches(query, elements) {
53
66
  return elements;
54
67
  return elements.filter((e) => e.name.length > 0 || (e.text ?? '').trim().length > 0);
55
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
+ }
56
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
+ }
57
113
  // Fields the browser's locator would have DROPPED, enforced back here — see residualQueryChecks.
58
114
  // Checked before the round-trip when nothing can enforce them: a predicate that cannot be evaluated
59
115
  // must say so rather than resolve to whatever the surviving half of it happened to match.
60
116
  const residual = residualQueryChecks(query);
61
117
  if (residual.unusable.length > 0) {
62
- const reason = `the element locator ignores ${residual.unusable.map((f) => `\`${f}\``).join(', ')} ` +
63
- `in ${JSON.stringify(query)} — it resolves by the first of by+value, component/source, role, ` +
64
- 'text, label, placeholder, testid, alt that is present, and nothing here can check the rest. ' +
65
- 'Assert them one locator at a time, or move the extra field into the locator';
118
+ const reason = describeUnusableElementQuery(query, residual.unusable);
66
119
  return { pass: false, failureReason: reason, inconclusive: reason };
67
120
  }
68
121
  let match = await matchOnce(session, query, state);
@@ -203,12 +256,73 @@ export async function evalElement(session, query, state, absent, diagnose) {
203
256
  const splitText = describeSplitTextMiss(match.hint?.splitText, query.text);
204
257
  const clause = splitText ?? (alsoHere === undefined || '' === alsoHere ? undefined : alsoHere);
205
258
  const suffix = clause === undefined ? '' : ` — ${clause}`;
259
+ // The evidence list is capped in document order, so a region low on the page is exactly what it
260
+ // drops. Handed back with no marker it reads as the whole page, and the field report this came
261
+ // from read a missing detail panel as proof the panel never rendered. Say the cut happened (#793).
262
+ const total = match.hint?.presentTestidsTotal;
263
+ const cut = describePresentTestidsCut(present.length, total);
206
264
  return {
207
265
  pass: false,
208
- failureReason: `no element matched ${subject}${state === undefined ? '' : ` in state '${state}'`}${suffix}`,
266
+ failureReason: `no element matched ${subject}${state === undefined ? '' : ` in state '${state}'`}${suffix}${cut}`,
209
267
  observed: `no matching element on the page${suffix}`,
210
268
  expected: `an element matching ${subject}${state === undefined ? '' : ` in state '${state}'`}`,
211
269
  assertion: 'element.present',
212
- ...(present.length > 0 ? { evidence: { presentTestids: present } } : {}),
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
274
+ ? {
275
+ evidence: {
276
+ ...(present.length > 0 ? { presentTestids: present } : {}),
277
+ ...(total === undefined || 0 === present.length ? {} : { presentTestidsTotal: total }),
278
+ ...(splitText === undefined ? {} : { splitText: match.hint?.splitText }),
279
+ },
280
+ }
281
+ : {}),
282
+ };
283
+ }
284
+ /**
285
+ * Narrow a passing text match with a PROPERTY of the text it found.
286
+ *
287
+ * Sits here rather than in the evaluator because the descriptors it reads are this module's own
288
+ * output shape, and because it must run only over a match that already held: a property asserted
289
+ * against the text of an element that is not there is a statement about nothing.
290
+ *
291
+ * Several matches are JOINED before the property runs. `scope` + `self` reads one subtree and is
292
+ * the shape this is for; a locator broad enough to return several is asking about the text they
293
+ * make together, and testing only the first would pass on a page where the rest is the failure.
294
+ */
295
+ /** The text an element descriptor reported, or ''. Never `String(unknown)` — see `show` in property.ts. */
296
+ function textOf(element) {
297
+ if ('object' !== typeof element || null === element)
298
+ return '';
299
+ const value = element.text;
300
+ return 'string' === typeof value ? value : '';
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
+ }
307
+ export function withTextProperty(base, assertion, subject, baseline) {
308
+ if (!base.pass)
309
+ return base;
310
+ const described = Array.isArray(base.evidence) ? base.evidence : [];
311
+ const text = joinedText(described);
312
+ const result = satisfiesProperty(text, assertion, baseline);
313
+ // Nothing was compared — a relative property with no before-reading. See the twin in `evalState`.
314
+ if (true === result.unevaluated) {
315
+ return { pass: false, failureReason: result.because, inconclusive: result.because };
316
+ }
317
+ if (result.ok) {
318
+ return { pass: true, evidence: { ...{ matched: described }, satisfied: result.because } };
319
+ }
320
+ return {
321
+ pass: false,
322
+ failureReason: `text of ${subject} ${result.because}`,
323
+ observed: `text of ${subject} = ${JSON.stringify(text)}`,
324
+ expected: `text of ${subject} to satisfy ${assertion.property}`,
325
+ assertion: `text.${assertion.property}`,
326
+ evidence: described,
213
327
  };
214
328
  }
@@ -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