@reticlehq/engine 3.3.0 → 3.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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);
@@ -14,8 +14,15 @@ export interface PredicateSession {
14
14
  command(name: string, args?: Record<string, unknown>, timeoutMs?: number): Promise<CommandResult>;
15
15
  eventsSince(cursor: number): ReticleEvent[];
16
16
  onEvent(listener: (event: ReticleEvent) => void): () => void;
17
+ /** Hold this wait's window against eviction while it is graded; returns the release (#668). */
18
+ protectWindow?(cursor: number): () => void;
17
19
  /** Milliseconds since connect — the same clock that stamps event `t` (injected, testable). */
18
20
  elapsed(): number;
21
+ /**
22
+ * The page SDK's package version from its hello, when it sent one. Read to refuse an element
23
+ * state the page is too old to answer (see ELEMENT_STATE_SINCE). Undefined for a hand-wired page.
24
+ */
25
+ sdkVersion?: string | undefined;
19
26
  /**
20
27
  * Where the app is RIGHT NOW — the session's live URL, kept current across SPA navigation.
21
28
  *
@@ -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.
@@ -370,6 +415,9 @@ baselines) {
370
415
  const reader = withinBudget(session, () => deadline - session.elapsed());
371
416
  return new Promise((resolve) => {
372
417
  let done = false;
418
+ // Released in `finish`, on every exit path. Without it a flood inside the window can evict the
419
+ // event the predicate is armed on, and the verdict blames the app (#668).
420
+ const releaseWindow = session.protectWindow?.(since);
373
421
  // A read that threw never looked at the app: the page did not answer, or went away. That is
374
422
  // "could not tell", not "looked and it was false", so it is inconclusive, which the verdict rule
375
423
  // turns into unknown. As a plain false it was graded assertion_failed: a command timeout on a
@@ -385,8 +433,9 @@ baselines) {
385
433
  let cooldownTimer;
386
434
  /** One-shot re-check timed to when a time-based predicate could first pass. See retryAfterMs. */
387
435
  let hintTimer;
388
- // An exact-count wait keeps watching after it first reads true — see COUNT_CONFIRM_MS.
389
- const holdsForCount = assertsExactCount(predicate);
436
+ // An exact count or an absence keeps watching after it first reads true — see COUNT_CONFIRM_MS
437
+ // and claimsAbsence.
438
+ const holdsForCount = assertsExactCount(predicate) || claimsAbsence(predicate);
390
439
  let confirming = false;
391
440
  let confirmTimer;
392
441
  /** Report a wait that could not run, and END it — see guardedCheck. */
@@ -405,6 +454,7 @@ baselines) {
405
454
  if (done)
406
455
  return;
407
456
  done = true;
457
+ releaseWindow?.();
408
458
  unsub();
409
459
  unsubDisconnect?.();
410
460
  clearInterval(interval);
@@ -551,6 +601,13 @@ baselines) {
551
601
  const timer = setTimeout(() => {
552
602
  void evaluatePredicate(reader, predicate, since, true, baselines)
553
603
  .then((r) => {
604
+ // A count or an absence that already read true and was holding to confirm: the caller's
605
+ // budget IS the end of its window, so this reading is the answer, whichever way it went.
606
+ // Forcing it to a fail would turn every honest absence under a short budget into a red.
607
+ if (confirming) {
608
+ finish(r);
609
+ return;
610
+ }
554
611
  // Spread the near-miss, do NOT hand-copy two fields. The oracle computes observed / expected
555
612
  // / assertion — the structured cause the repair literature ranks above prose — and the old
556
613
  // `{ pass, evidence, failureReason }` construction DISCARDED them on every timed-out wait and
@@ -24,6 +24,20 @@ export declare class RingBuffer {
24
24
  since(cursor: number): ReticleEvent[];
25
25
  /** Events within the last `windowMs`, relative to `now`. */
26
26
  window(windowMs: number, now: number): ReticleEvent[];
27
+ /**
28
+ * Protect events at or after `cursor` from count-cap eviction until the returned function runs.
29
+ *
30
+ * Call it when a wait arms and call the result when the verdict is graded, in a `finally`: a
31
+ * leaked protection would hold the allowance open for the life of the session. Releasing twice is
32
+ * harmless.
33
+ *
34
+ * This is a bounded promise, not an absolute one. Past {@link ARMED_WINDOW_OVERFLOW} events, or
35
+ * under byte pressure, the window is evicted anyway and the loss is recorded as scarce -- so
36
+ * `lostSince` turns the verdict undecidable instead of returning the false red that pinning
37
+ * exists to prevent. Degrading into "I could not see" is right; degrading into "it did not
38
+ * happen" is the defect.
39
+ */
40
+ protect(cursor: number): () => void;
27
41
  /**
28
42
  * Did this buffer evict scarce evidence that belonged to a window opened at `cursor`?
29
43
  *