@reticlehq/engine 3.4.0 → 3.6.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 (35) hide show
  1. package/dist/disagreement/body-failures.js +2 -1
  2. package/dist/disagreement/contradiction-evidence.d.ts +7 -0
  3. package/dist/disagreement/contradiction-evidence.js +13 -4
  4. package/dist/disagreement/contradictions.d.ts +5 -1
  5. package/dist/disagreement/contradictions.js +109 -3
  6. package/dist/disagreement/echo-mismatch.js +42 -3
  7. package/dist/disagreement/reconcile.js +15 -0
  8. package/dist/disagreement/stale-response.js +32 -2
  9. package/dist/evidence/accepted-write.d.ts +26 -2
  10. package/dist/evidence/accepted-write.js +35 -18
  11. package/dist/evidence/already-true.d.ts +11 -0
  12. package/dist/evidence/already-true.js +27 -0
  13. package/dist/evidence/body-capture-remedy.d.ts +10 -0
  14. package/dist/evidence/body-capture-remedy.js +15 -2
  15. package/dist/evidence/verified.d.ts +2 -0
  16. package/dist/evidence/verified.js +10 -0
  17. package/dist/question/declared.d.ts +4 -4
  18. package/dist/question/declared.js +6 -4
  19. package/dist/question/predicate/name-near-miss.d.ts +24 -0
  20. package/dist/question/predicate/name-near-miss.js +39 -0
  21. package/dist/question/predicate/predicate-compare.js +13 -4
  22. package/dist/question/predicate/predicate-element.d.ts +1 -1
  23. package/dist/question/predicate/predicate-element.js +33 -3
  24. package/dist/question/predicate/predicate-eval.d.ts +16 -1
  25. package/dist/question/predicate/predicate-eval.js +70 -13
  26. package/dist/question/predicate/predicate-parse.js +119 -13
  27. package/dist/question/predicate/predicate-schema.js +58 -23
  28. package/dist/question/predicate/predicate-session.d.ts +12 -0
  29. package/dist/question/predicate/predicate-to-links.js +1 -0
  30. package/dist/question/predicate/predicate.js +76 -15
  31. package/dist/question/reaction.d.ts +1 -1
  32. package/dist/question/reaction.js +1 -1
  33. package/dist/window/ring-buffer.d.ts +14 -0
  34. package/dist/window/ring-buffer.js +69 -1
  35. package/package.json +3 -3
@@ -124,10 +124,10 @@ export function declaredExpectations(predicate) {
124
124
  * verdict (measured: a 201 plus the unique row, unread body, agent went to enable capture instead
125
125
  * of finishing the drive).
126
126
  *
127
- * Same conservatism as `declaredExpectations`: only the top level and `allOf`. An `anyOf` branch
128
- * may never have held, and honouring it would skip the unread caveat on the strength of a net
129
- * success that was the branch that actually matched. An `absent` element is not a consequence the
130
- * body cannot own.
127
+ * Same conservatism as `declaredExpectations`: only the top level and `allOf`, plus an `anyOf` whose
128
+ * every branch is body-independent. An `anyOf` with a net branch may have held on that branch alone,
129
+ * so it must not skip the unread caveat. An `absent` element is not a consequence the body cannot
130
+ * own.
131
131
  */
132
132
  export function declaresBodyIndependentChannel(predicate) {
133
133
  if (predicate === undefined)
@@ -136,6 +136,8 @@ export function declaresBodyIndependentChannel(predicate) {
136
136
  switch (p.kind) {
137
137
  case PredicateKind.ALL_OF:
138
138
  return p.predicates.some(walk);
139
+ case PredicateKind.ANY_OF:
140
+ return p.predicates.every(walk);
139
141
  case PredicateKind.TEXT:
140
142
  return true !== p.absent;
141
143
  case PredicateKind.SIGNAL:
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The "…but that role IS carrying this label" clause on a failed element predicate.
3
+ *
4
+ * `reticle_query` answers a role+name miss with `hint.nameNearMiss` -- the labels that role really
5
+ * has, when one of them is a containment away from the one asked for. A failed PREDICATE had no
6
+ * equivalent: `no element matched {role: "button", name: "Mesh"}` is byte-identical for a page with
7
+ * no such button and for one showing `button "2 Mesh"`, and only one of those is a bug (#875).
8
+ *
9
+ * That asymmetry is the same one `describeSplitTextMiss` was written to close one field over: the
10
+ * identical failure through `reticle_query` listed what IS present while the predicate path was a
11
+ * dead end. The browser already computes this on its way to reporting zero, so the clause costs
12
+ * nothing but the sentence.
13
+ *
14
+ * Undefined when there is nothing to say, for the reason every clause in this family is: one that
15
+ * fires on every failure stops carrying information.
16
+ */
17
+ /**
18
+ * The clause, or undefined when the page carried no near-miss label.
19
+ *
20
+ * `role` is named in the sentence because the hint is scoped to it: the browser will not offer a
21
+ * link called "2 Mesh" as a recovery for a BUTTON called "Mesh", and the message should not read as
22
+ * if it might have.
23
+ */
24
+ export declare function describeNameNearMiss(near: readonly string[] | undefined, searchedName?: string, role?: string): string | undefined;
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The "…but that role IS carrying this label" clause on a failed element predicate.
3
+ *
4
+ * `reticle_query` answers a role+name miss with `hint.nameNearMiss` -- the labels that role really
5
+ * has, when one of them is a containment away from the one asked for. A failed PREDICATE had no
6
+ * equivalent: `no element matched {role: "button", name: "Mesh"}` is byte-identical for a page with
7
+ * no such button and for one showing `button "2 Mesh"`, and only one of those is a bug (#875).
8
+ *
9
+ * That asymmetry is the same one `describeSplitTextMiss` was written to close one field over: the
10
+ * identical failure through `reticle_query` listed what IS present while the predicate path was a
11
+ * dead end. The browser already computes this on its way to reporting zero, so the clause costs
12
+ * nothing but the sentence.
13
+ *
14
+ * Undefined when there is nothing to say, for the reason every clause in this family is: one that
15
+ * fires on every failure stops carrying information.
16
+ */
17
+ /** Enough of a label to recognise it; this is read in a verdict, not a log. */
18
+ const MAX_NAME = 60;
19
+ /** At most this many alternatives in one sentence -- beyond that it is a result set, not a hint. */
20
+ const MAX_NAMED = 3;
21
+ function truncate(value) {
22
+ return value.length > MAX_NAME ? `${value.slice(0, MAX_NAME)}…` : value;
23
+ }
24
+ /**
25
+ * The clause, or undefined when the page carried no near-miss label.
26
+ *
27
+ * `role` is named in the sentence because the hint is scoped to it: the browser will not offer a
28
+ * link called "2 Mesh" as a recovery for a BUTTON called "Mesh", and the message should not read as
29
+ * if it might have.
30
+ */
31
+ export function describeNameNearMiss(near, searchedName, role) {
32
+ if (near === undefined || 0 === near.length)
33
+ return undefined;
34
+ const labels = near.slice(0, MAX_NAMED).map((name) => JSON.stringify(truncate(name)));
35
+ const asked = searchedName === undefined ? 'that name' : JSON.stringify(truncate(searchedName));
36
+ const what = role === undefined ? 'the page has' : `the page's ${role}s include`;
37
+ return (`role+name matching is EXACT and nothing is named ${asked}, but ${what} ${labels.join(', ')} — ` +
38
+ 're-query with the full name rather than a substring of it');
39
+ }
@@ -139,10 +139,11 @@ function readSide(session, events, source, diagnose) {
139
139
  }
140
140
  }
141
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.
142
+ * A thousands-grouped number or a plain one, optionally preceded by a minus sign and/or a currency
143
+ * symbol (`-$100`, `-₹1,187.01`). A comma counts as a separator only in groups of three, so `11,87`
144
+ * (a decimal comma) reads as two numbers, not as 1187 — and two numbers are refused.
144
145
  */
145
- const NUMBER_TOKEN = /-?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?/g;
146
+ const NUMBER_TOKEN = /(?:-(?:[\p{Sc}]\s*)?|[\p{Sc}]\s*-?)?(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?/gu;
146
147
  /** One number out of a reading, or why there is not exactly one. */
147
148
  function numberOf(value) {
148
149
  if ('number' === typeof value)
@@ -156,7 +157,15 @@ function numberOf(value) {
156
157
  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
  };
158
159
  }
159
- return { n: Number(only.replace(/,/g, '')) };
160
+ const isNegative = only.includes('-');
161
+ const cleaned = only.replace(/,/g, '');
162
+ const digits = cleaned.match(/(?:\d+(?:\.\d+)?)/);
163
+ if (null === digits) {
164
+ return { why: `could not parse a number from ${JSON.stringify(value)}` };
165
+ }
166
+ const parsed = Number(digits[0]);
167
+ const n = isNegative && 0 !== parsed ? -parsed : parsed;
168
+ return { n };
160
169
  }
161
170
  /**
162
171
  * A few units in the last place: the noise of arithmetic done in binary (`0.1 + 0.2` against the
@@ -6,7 +6,7 @@
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 } from '@reticlehq/core';
9
+ import { type ElementQuery, ElementState } from '@reticlehq/core';
10
10
  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';
@@ -6,11 +6,12 @@
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 { ReticleCommand, } from '@reticlehq/core';
9
+ import { QueryBy, ReticleCommand, ElementState, } from '@reticlehq/core';
10
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';
14
+ import { describeNameNearMiss } from './name-near-miss.js';
14
15
  /**
15
16
  * The caveat for a present-testid list that was cut at its cap, or nothing when it was whole.
16
17
  *
@@ -23,6 +24,27 @@ function describePresentTestidsCut(shown, total) {
23
24
  return '';
24
25
  return ` (the present-testid list shows the first ${String(shown)} of ${String(total)} in document order — absence from it proves nothing)`;
25
26
  }
27
+ /**
28
+ * Why an `absent` check failed. `absent` means removed from the DOM, so an element the app hid but
29
+ * kept mounted still fails it, correctly. But "found 1" beside `visible: false` evidence reads as a
30
+ * stuck UI, so when every match is hidden the reason says so and names `state: "hidden"`, the
31
+ * predicate for "no longer shown" (#1360). Only when every match was described: with a truncated
32
+ * list a visible one may be among the rest, and the hint would then be wrong. And only when the
33
+ * check names no state: with `state: "hidden"` the advice would repeat the check itself, and with any
34
+ * other state it would ask the caller to drop the condition they actually wrote.
35
+ */
36
+ function describeAbsentMiss(match, state) {
37
+ const found = `expected element to be absent but found ${String(match.count)}`;
38
+ const allDescribedHidden = undefined === state &&
39
+ match.elements.length > 0 &&
40
+ match.elements.length === match.count &&
41
+ match.elements.every((element) => !element.visible);
42
+ if (!allDescribedHidden)
43
+ return found;
44
+ const which = 1 === match.count ? 'it is' : 'every one is';
45
+ return (`${found}, but ${which} hidden — \`absent\` means removed from the DOM; ` +
46
+ `to assert it isn't shown, use \`state: "${ElementState.HIDDEN}"\``);
47
+ }
26
48
  async function matchOnce(session, query, state) {
27
49
  const res = await session.command(ReticleCommand.MATCH, { query, state });
28
50
  if (!res.ok)
@@ -161,7 +183,7 @@ export async function evalElement(session, query, state, absent, diagnose) {
161
183
  return match.matched
162
184
  ? {
163
185
  pass: false,
164
- failureReason: `expected element to be absent but found ${String(match.count)}`,
186
+ failureReason: describeAbsentMiss(match, state),
165
187
  observed: `${String(match.count)} element(s) matching ${subject}`,
166
188
  expected: `no element matching ${subject}`,
167
189
  assertion: 'element.absent',
@@ -254,7 +276,15 @@ export async function evalElement(session, query, state, absent, diagnose) {
254
276
  // element that never rendered. Naming the container is the difference between a retry and a bug
255
277
  // report against working code. See split-text-miss.ts.
256
278
  const splitText = describeSplitTextMiss(match.hint?.splitText, query.text);
257
- const clause = splitText ?? (alsoHere === undefined || '' === alsoHere ? undefined : alsoHere);
279
+ // Same asymmetry one field over: an exact role+name miss reads like an element that never
280
+ // rendered, while the identical failure through reticle_query lists the labels that role really
281
+ // has. The browser computed them on its way to reporting zero. See name-near-miss.ts.
282
+ // Scoped by role in both spellings, as `query.ts` resolves it: `{ by: 'role', value, name }` carries
283
+ // the role in `value`, and without this the sentence said "the page has" for a list the browser had
284
+ // already limited to that role.
285
+ const nearMissRole = QueryBy.ROLE === query.by ? query.value : query.role;
286
+ const nearMiss = describeNameNearMiss(match.hint?.nameNearMiss, query.name, nearMissRole);
287
+ const clause = splitText ?? nearMiss ?? (alsoHere === undefined || '' === alsoHere ? undefined : alsoHere);
258
288
  const suffix = clause === undefined ? '' : ` — ${clause}`;
259
289
  // The evidence list is capped in document order, so a region low on the page is exactly what it
260
290
  // drops. Handed back with no marker it reads as the whole page, and the field report this came
@@ -19,6 +19,21 @@ export declare function evalAnimation(events: ReticleEvent[], p: Extract<Predica
19
19
  export declare function evalSignal(events: ReticleEvent[], p: Extract<Predicate, {
20
20
  kind: typeof PredicateKind.SIGNAL;
21
21
  }>): EvalResult;
22
+ /**
23
+ * What the caller knows about whose traffic this is.
24
+ *
25
+ * Both members are OPTIONAL and both fail OPEN. `settled` used to answer "has the app finished?" over
26
+ * whatever bytes were in the buffer, so a request that no other settle decision counts could hold it
27
+ * open forever — and an assertion that can never pass is one agents delete from their `until`, which
28
+ * costs them the honesty the predicate exists to provide. The fix is to ask the same two questions
29
+ * the act wait asks; the caller who cannot answer them gets exactly the behaviour this had before.
30
+ */
31
+ export interface SettleScope {
32
+ /** The page under test — what makes a request third-party. Absent: nothing is foreign. */
33
+ appUrl?: string | undefined;
34
+ /** Same-origin endpoints the project declared as background. Absent: nothing is excluded. */
35
+ background?: readonly string[] | undefined;
36
+ }
22
37
  /**
23
38
  * "The page has gone quiet": no network/DOM/animation activity for at least `quietMs`. Needs the
24
39
  * wall-clock `now` (in the buffer's time base) because "no activity in the last N ms" is relative to
@@ -27,4 +42,4 @@ export declare function evalSignal(events: ReticleEvent[], p: Extract<Predicate,
27
42
  */
28
43
  export declare function evalSettled(allEvents: ReticleEvent[], p: Extract<Predicate, {
29
44
  kind: typeof PredicateKind.SETTLED;
30
- }>, now: number): EvalResult;
45
+ }>, now: number, scope?: SettleScope): EvalResult;
@@ -1,4 +1,4 @@
1
- import { EventType, PredicateKind, StreamDirection, isDevToolingUrl, urlForMatch, REDACTED_VALUE, } from '@reticlehq/core';
1
+ import { EventType, NetInitiator, PredicateKind, StreamDirection, isDevToolingUrl, isForeignTraffic, urlForMatch, REDACTED_VALUE, } from '@reticlehq/core';
2
2
  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';
@@ -684,30 +684,87 @@ const NET_TYPES = new Set([
684
684
  ]);
685
685
  /** Default quiet window — enough to absorb a render+xhr settle without waiting on slow polls. */
686
686
  const DEFAULT_QUIET_MS = 500;
687
+ /**
688
+ * Did the browser LEAVE for this record, rather than make a request whose result we will see?
689
+ *
690
+ * `NetInitiator.NAVIGATION` is emitted as a `NET_PENDING` — because that is exactly what it is — but
691
+ * its completion goes to a document this session does not live into, so no `NET_REQUEST` can ever
692
+ * match it. Counting it as outstanding means the first click on any outbound link or download button
693
+ * wedges settle on that page for the rest of the session.
694
+ *
695
+ * The act wait (`server/src/surface/tools/act/settle-in-flight.ts`) has always excluded it and
696
+ * `core/src/wire/net.ts` says it must be; this predicate counted it, so `act_and_wait { until:
697
+ * settled }` after a plain `<a href>` never passed and agents dropped `settled` from their `until`.
698
+ * Spelled against the shared constant rather than the string, so the two settle decisions cannot
699
+ * drift onto two vocabularies.
700
+ */
701
+ const isDeparture = (data) => data['initiator'] === NetInitiator.NAVIGATION;
687
702
  /**
688
703
  * "The page has gone quiet": no network/DOM/animation activity for at least `quietMs`. Needs the
689
704
  * wall-clock `now` (in the buffer's time base) because "no activity in the last N ms" is relative to
690
705
  * now, not to any buffered event — so `now` is injected (CLAUDE.md rule 7), and the wait loop's
691
706
  * poll interval is what eventually flips this to pass once activity stops.
692
707
  */
693
- export function evalSettled(allEvents, p, now) {
708
+ export function evalSettled(allEvents, p, now, scope) {
694
709
  const quietMs = p.quietMs ?? DEFAULT_QUIET_MS;
695
- // Dev-tooling traffic is the framework talking about ITSELF (see DevToolingChannel) and says
696
- // nothing about whether the app finished its work — but it was holding settle open. Dropped from
697
- // both halves of the calculation below (in-flight AND the quiet timer) and DISCLOSED on the
698
- // evidence, never silently swallowed.
710
+ // Three kinds of traffic say nothing about whether the APP finished its work, and all three are
711
+ // dropped from BOTH halves of the calculation below (in-flight AND the quiet timer) and DISCLOSED
712
+ // on the evidence, never silently swallowed:
713
+ //
714
+ // - dev tooling, the framework talking about ITSELF (see DevToolingChannel);
715
+ // - a departure, which by construction can never complete (see `NetInitiator.NAVIGATION`);
716
+ // - somebody else's host, or a same-origin endpoint the project declared (`isForeignTraffic`).
717
+ //
718
+ // The last two were counted here while `settle-in-flight.ts` and the contradiction pass dropped
719
+ // them, so the product held two answers to one question. The predicate's answer was the wrong one:
720
+ // after a plain `<a href>` click it reported "1 request(s) still in flight" forever, and a vendor
721
+ // beacon made every assertion on such an app return `unknown / outcome_pending`.
722
+ //
723
+ // A departure is kept APART from foreign traffic all the way into the disclosure. The two are one
724
+ // CLASSIFICATION and two EXPLANATIONS — both drop out of the count, but "the page left for another
725
+ // document" and "somebody else's host answered" send a reader to different next steps, and one
726
+ // list holding both makes the second the only thing the first can be read as.
699
727
  const ignoredDevTooling = [];
728
+ const ignoredForeign = [];
729
+ const ignoredDepartures = [];
700
730
  const events = allEvents.filter((e) => {
701
731
  if (!NET_TYPES.has(e.type))
702
732
  return true;
703
- const url = str(e.data['url']);
704
- if (!isDevToolingUrl(url))
705
- return true;
706
- if (url !== undefined && !ignoredDevTooling.includes(url))
707
- ignoredDevTooling.push(url);
708
- return false;
733
+ // Classified by `urlForMatch`, DISCLOSED by `url`: redaction rewrites sensitive path segments at
734
+ // emit time (`/auth/token/refresh-context` -> `/auth/token/[REDACTED]`), and a declared
735
+ // `background` pattern is matched with `String.includes` — so classifying on the displayed URL
736
+ // would let a redacted segment put the endpoint back in the in-flight count, which is the defect
737
+ // this whole branch exists to fix. The haystack is the raw request; the transcript gets the
738
+ // displayed one. Same division of labour `urlContains` uses at the top of this file.
739
+ const matchUrl = urlForMatch(e.data);
740
+ const shown = str(e.data['url']);
741
+ if (isDevToolingUrl(matchUrl)) {
742
+ if (shown !== undefined && !ignoredDevTooling.includes(shown))
743
+ ignoredDevTooling.push(shown);
744
+ return false;
745
+ }
746
+ // Departure first: a departure to the app's own origin is still a request whose result nobody
747
+ // will see, and reporting it as somebody else's host would be the wrong explanation.
748
+ if (isDeparture(e.data)) {
749
+ if (shown !== undefined && !ignoredDepartures.includes(shown))
750
+ ignoredDepartures.push(shown);
751
+ return false;
752
+ }
753
+ if (isForeignTraffic(matchUrl, scope?.appUrl, scope?.background ?? [])) {
754
+ if (shown !== undefined && !ignoredForeign.includes(shown))
755
+ ignoredForeign.push(shown);
756
+ return false;
757
+ }
758
+ return true;
709
759
  });
710
- const disclosure = 0 === ignoredDevTooling.length ? {} : { ignoredDevTooling };
760
+ // Three separate lists rather than one: "the framework talking about itself", "the page left", and
761
+ // "somebody else's host" are three different facts about a window, and a reader told only one of
762
+ // them has to guess which it was.
763
+ const disclosure = {
764
+ ...(0 === ignoredDevTooling.length ? {} : { ignoredDevTooling }),
765
+ ...(0 === ignoredForeign.length ? {} : { ignoredForeign }),
766
+ ...(0 === ignoredDepartures.length ? {} : { ignoredDepartures }),
767
+ };
711
768
  // A request that STARTED (NET_PENDING) but never completed (NET_REQUEST with the same id) is
712
769
  // still in flight — the page is NOT settled no matter how quiet the DOM has gone. Without this,
713
770
  // a slow save reads as "settled" the instant its spinner stops mutating the DOM: the exact
@@ -98,9 +98,8 @@ export function parsePredicate(input) {
98
98
  const parsed = PredicateSchema.safeParse(input);
99
99
  if (parsed.success)
100
100
  return parsed.data;
101
- const kind = 'object' === typeof input && null !== input && 'kind' in input
102
- ? String(input['kind'])
103
- : 'unknown';
101
+ const asWritten = kindAsWritten(input);
102
+ const kind = 'string' === typeof asWritten ? asWritten : 'unknown';
104
103
  // Bounded on purpose: a union rejection can produce one issue per member, and pasting all of them
105
104
  // back is how the zod array became unreadable in the first place.
106
105
  const issues = parsed.error.issues.slice(0, 3).map(describeIssue).join('; ');
@@ -126,20 +125,127 @@ const CALL_LEVEL_FIELDS = [
126
125
  'target',
127
126
  'intent',
128
127
  ];
128
+ /** The fields that carry a predicate inside a predicate — `anyOf`/`allOf`, and `not`. */
129
+ const NESTED_PREDICATE_FIELDS = ['predicates', 'predicate'];
130
+ /**
131
+ * `type`, read as the discriminator when — and only when — `kind` is absent.
132
+ *
133
+ * Spelled here rather than imported: core keeps this constant private, and `core-coupling-only-
134
+ * shrinks` counts every name the engine borrows — a one-word alias is not worth a permanent one.
135
+ * The two are held together by a test instead, so a change to the alias fails here rather than
136
+ * silently reintroducing the `kind "unknown"` reading this fixes.
137
+ */
138
+ const KIND_ALIAS = 'type';
139
+ /**
140
+ * How many locator clauses one rejection carries before the rest are counted instead.
141
+ *
142
+ * A rejected `anyOf`/`allOf` produces one clause per invalid member, and unlike the three-issue
143
+ * limit on schema errors these had none — so a single tool error could grow into the same sentence
144
+ * repeated until the advice that was asked for was the hardest thing in it to find.
145
+ */
146
+ const MAX_LOCATOR_CLAUSES = 3;
147
+ /** The clause for a `ref` beside a `query` that already holds a locator. */
148
+ const ELEMENT_REF_DELETE_CLAUSE = '`ref` is not a field of an `element` predicate: the locator already sits in `query`, ' +
149
+ 'so delete the `ref` rather than moving it up beside `until`.';
150
+ /** The clause for a `ref` written where the locator belongs, naming the fields `query` accepts. */
151
+ function elementRefMoveClause(queryFields) {
152
+ return ('`ref` is not a locator on an `element` predicate: element predicates take `query` ' +
153
+ `(${queryFields}), not \`ref\` — put the locator inside \`query\`; a raw element ref ` +
154
+ 'belongs in `query.scope`.');
155
+ }
156
+ /**
157
+ * Whether a written `query` actually carries a locator.
158
+ *
159
+ * `{}` is accepted by the schema and locates nothing, so presence of the key is not the question.
160
+ * Reading it as "the locator is already there" told the caller to delete the only target it had.
161
+ */
162
+ function carriesLocator(query) {
163
+ return 'object' === typeof query && null !== query && 0 < Object.keys(query).length;
164
+ }
165
+ /**
166
+ * The kind as written, reading core's `type` spelling when `kind` is absent.
167
+ *
168
+ * `PredicateSchema` accepts `type` as the discriminator whenever `kind` is missing — core normalises
169
+ * it in `applyPredicateAliases` before parsing, and an explicit `kind` still wins. Reading `kind`
170
+ * alone here is how `{ type: 'element', ref: 'e1' }` came back as `kind "unknown"` carrying the very
171
+ * #1374 advice the canonical spelling no longer gets. One reader for the sentence and the clause, so
172
+ * the two cannot disagree about which kind was written.
173
+ */
174
+ function kindAsWritten(input) {
175
+ if ('object' !== typeof input || null === input)
176
+ return undefined;
177
+ const obj = input;
178
+ return obj['kind'] !== undefined ? obj['kind'] : obj[KIND_ALIAS];
179
+ }
129
180
  /** The clause naming where a misplaced call argument goes, or '' when nothing was misplaced. */
130
181
  function misplacedCallFields(input) {
182
+ const clauses = [...new Set(misplacedClauses(input))];
183
+ // Bounded like the issue list above, and for the same reason: one rejected `anyOf` can carry an
184
+ // invalid `element` per member, and a clause each turns one tool error into a wall of the same
185
+ // sentence — which buries the advice instead of delivering it. The count is named rather than
186
+ // silently dropped, so a caller with a genuinely long list knows to look at the members.
187
+ const shown = clauses.slice(0, MAX_LOCATOR_CLAUSES);
188
+ const rest = clauses.length - shown.length;
189
+ if (0 < rest)
190
+ shown.push(`${rest} more predicate${1 === rest ? '' : 's'} need the same fix.`);
191
+ return 0 === shown.length ? '' : ` ${shown.join(' ')}`;
192
+ }
193
+ /**
194
+ * The clauses for this object, plus the same reading one level down.
195
+ *
196
+ * `anyOf`/`allOf` wrap a predicate, and wrapping the first `element` assertion of a session in one is
197
+ * an ordinary way to write it — so the `ref`-as-locator answer has to reach that level too, or the
198
+ * fix holds only for the spellings that happen to be top-level. The walk is bounded by the number of
199
+ * clauses reported rather than by depth: the schema nests without limit, and a depth cutoff answered
200
+ * `allOf → not → anyOf → element` with the error this change exists to explain.
201
+ */
202
+ function misplacedClauses(input) {
131
203
  if ('object' !== typeof input || null === input)
132
- return '';
204
+ return [];
205
+ const obj = input;
133
206
  const written = Object.keys(input);
134
- const misplaced = CALL_LEVEL_FIELDS.filter((field) => written.includes(field));
135
- if (0 === misplaced.length)
136
- return '';
137
- const list = misplaced.join(', ');
138
- // Named as a MOVE, not as a removal. Deleting the field is the reading of "unknown field" that
139
- // costs the caller the thing it asked for.
140
- return (` ${list} ${1 === misplaced.length ? 'is an argument' : 'are arguments'} of the CALL, not of ` +
141
- `the predicate: ${1 === misplaced.length ? 'move it' : 'move them'} up beside \`until\` rather ` +
142
- 'than dropping it — nesting is why the predicate did not parse.');
207
+ const clauses = [];
208
+ // `element` is the one kind where a `ref` is not a call argument one level too deep but a locator
209
+ // written in the wrong place: the locator nests under `query`, so the retry is to move it inside
210
+ // `query` — not up beside `until`. That advice is misdirection here: on `act_and_wait` moving a
211
+ // `ref` up retargets the ACTION, and `reticle_assert` has no `until` at all, so the caller loses
212
+ // its target and still does not parse. Named as the field to write instead, so the retry keeps it.
213
+ //
214
+ // `ref: undefined` is not a locator written in the wrong place, so the clause keys off a value
215
+ // rather than off the key being present.
216
+ const kind = kindAsWritten(input);
217
+ const refIsLocator = 'string' === typeof kind && PredicateKind.ELEMENT === kind && obj['ref'] !== undefined;
218
+ if (refIsLocator) {
219
+ // The locator may ALREADY be in `query`, and then the only thing to do is delete the extra
220
+ // `ref`. "Put the locator inside `query`" would send the caller to rewrite a field that is
221
+ // already right — a worse retry than the one it replaces. Derived from the schema rather than
222
+ // listed here: a stale field list is worse than none, because the agent trusts it and retries
223
+ // into the same wall.
224
+ //
225
+ // An EMPTY `query` is not a locator: `{}` parses, and deleting the `ref` as told would leave
226
+ // the predicate with no target at all. So the "already there" reading keys off `query`
227
+ // carrying at least one field, not off the key being present.
228
+ const queryFields = (predicateNestedFieldsFor(PredicateKind.ELEMENT)['query'] ?? []).join('/');
229
+ clauses.push(carriesLocator(obj['query']) ? ELEMENT_REF_DELETE_CLAUSE : elementRefMoveClause(queryFields));
230
+ }
231
+ const misplaced = CALL_LEVEL_FIELDS.filter((field) => written.includes(field) && !(refIsLocator && 'ref' === field));
232
+ if (0 < misplaced.length) {
233
+ const list = misplaced.join(', ');
234
+ // Named as a MOVE, not as a removal. Deleting the field is the reading of "unknown field" that
235
+ // costs the caller the thing it asked for.
236
+ clauses.push(`${list} ${1 === misplaced.length ? 'is an argument' : 'are arguments'} of the CALL, not of ` +
237
+ `the predicate: ${1 === misplaced.length ? 'move it' : 'move them'} up beside \`until\` rather ` +
238
+ 'than dropping it — nesting is why the predicate did not parse.');
239
+ }
240
+ for (const field of NESTED_PREDICATE_FIELDS) {
241
+ const child = obj[field];
242
+ if (child === undefined)
243
+ continue;
244
+ for (const nested of Array.isArray(child) ? child : [child]) {
245
+ clauses.push(...misplacedClauses(nested));
246
+ }
247
+ }
248
+ return clauses;
143
249
  }
144
250
  /**
145
251
  * What WOULD have worked, in the same breath as what did not.
@@ -12,25 +12,15 @@ import { PredicateKind, PredicateSchema, QueryBy, predicateShapeFor, } from '@re
12
12
  // One public surface, two packages. A caller asking this module for the shape is asking the right
13
13
  // module; it simply no longer OWNS it.
14
14
  export { PredicateSchema } from '@reticlehq/core';
15
- /**
16
- * Element-query fields an agent writes FLAT on an `element` predicate instead of nested under
17
- * `query`. `reticle_query` takes exactly these at the top level, so an agent that has just located
18
- * something writes the same words again when it asserts on it — and got `query: Required` plus an
19
- * `unknown field` list for its trouble. Lifting them is unambiguous: they have no other meaning on
20
- * this kind.
15
+ /*
16
+ * This file used to keep its own list of element-query fields, and issue #1375 is what that cost:
17
+ *
18
+ * core's copy had fallen four fields behind `ElementQuerySchema` (`scope`, `self`,
19
+ * `attrs`, `source`) while this one had not, so the two disagreed about what a flat element
20
+ * predicate may say. The list is gone: `residualQueryChecks` walks the query's OWN keys instead —
21
+ * the fields the caller actually wrote — which cannot fall behind a schema the query was parsed
22
+ * against, and costs no new core import (the engine's borrow count is a ceiling, not a budget).
21
23
  */
22
- const ELEMENT_QUERY_FIELDS = [
23
- 'by',
24
- 'value',
25
- 'role',
26
- 'name',
27
- 'text',
28
- 'label',
29
- 'placeholder',
30
- 'testid',
31
- 'alt',
32
- 'component',
33
- ];
34
24
  /**
35
25
  * The locator fields the browser actually CONSUMES for a given query — mirrors the precedence in
36
26
  * `findIn` (adapters/realm/browser/src/dom/query.ts).
@@ -46,6 +36,24 @@ const ELEMENT_QUERY_FIELDS = [
46
36
  */
47
37
  function usedQueryFields(query) {
48
38
  const used = new Set();
39
+ // `scope`, `attrs` and `self` are not locator fields, so no branch below consumes them and none is
40
+ // dropped: `scope` narrows WHERE the search runs (resolved before any locator branch runs),
41
+ // `attrs` projects the match, and `self` selects the scope root. Claiming these here — whatever
42
+ // their value — is what keeps them from being refused for merely existing.
43
+ //
44
+ // `source` is deliberately NOT one of them. It IS a locator — the anchor `component` is, consumed
45
+ // on exactly the same two branches — and it is claimed there and only there. Claiming it here too
46
+ // is what let a `by`+`value` query, or a `self: true` one, report the locator as having used a
47
+ // `source` it never read: the browser resolves those by `by`+`value` (or the scope root) and
48
+ // returns before `findBySource` is reached, so the predicate could pass for an element other than
49
+ // the one the caller's source location identified. Unclaimed, it falls through to the residual
50
+ // walk and is refused — exactly as `component` already is in the same position.
51
+ if (query.scope !== undefined)
52
+ used.add('scope');
53
+ if (query.attrs !== undefined)
54
+ used.add('attrs');
55
+ if (query.self !== undefined)
56
+ used.add('self');
49
57
  // The browser's `self` branch checks subtree text when supplied, but skips every other locator.
50
58
  // Mark only text as consumed so role/name/etc. remain residual checks on the returned descriptor.
51
59
  if (true === query.self)
@@ -54,12 +62,22 @@ function usedQueryFields(query) {
54
62
  used.add('by').add('value');
55
63
  if (QueryBy.ROLE === query.by)
56
64
  used.add('name');
57
- if (QueryBy.COMPONENT === query.by)
65
+ // `by: "component"` resolves through `findByComponent`, which tries the source stamp first and
66
+ // falls back to the component name — so a `source` written here IS consumed.
67
+ if (QueryBy.COMPONENT === query.by) {
58
68
  used.add('component');
69
+ if (query.source !== undefined)
70
+ used.add('source');
71
+ }
72
+ return used;
73
+ }
74
+ // The auto-anchor branch, reached only without `by`+`value`: `source` (precise) then `component`.
75
+ if (query.component !== undefined || query.source !== undefined) {
76
+ used.add('component');
77
+ if (query.source !== undefined)
78
+ used.add('source');
59
79
  return used;
60
80
  }
61
- if (query.component !== undefined || query.source !== undefined)
62
- return used.add('component');
63
81
  if (query.role !== undefined)
64
82
  return used.add('role').add('name');
65
83
  for (const field of ['text', 'label', 'placeholder', 'testid', 'alt']) {
@@ -83,9 +101,23 @@ function usedQueryFields(query) {
83
101
  * Testing Library's `exact: false`, and falls back to the name because describe() omits `text` when it
84
102
  * equals the accessible name.
85
103
  */
104
+ /**
105
+ * Does an element whose computed role is `actual` satisfy a query for `queried`?
106
+ *
107
+ * `searchbox` is an ARIA sub-role of `textbox`. A standard search input computes as `searchbox`
108
+ * (per HTML-AAM), which matches `{ role: "searchbox" }`. A `{ role: "textbox" }` query must
109
+ * keep matching it as well, so existing flows and recorded steps using `textbox` continue to match.
110
+ */
111
+ function matchesRole(actual, queried) {
112
+ if (actual === queried)
113
+ return true;
114
+ if ('textbox' === queried && 'searchbox' === actual)
115
+ return true;
116
+ return false;
117
+ }
86
118
  const RESIDUAL_CHECKS = {
87
119
  value: (element, want) => (element.value ?? '').trim() === want.trim(),
88
- role: (element, want) => element.role === want,
120
+ role: (element, want) => matchesRole(element.role, want),
89
121
  name: (element, want) => element.name.trim() === want.trim(),
90
122
  text: (element, want) => (element.text ?? element.name).includes(want),
91
123
  };
@@ -101,7 +133,10 @@ export function residualQueryChecks(query) {
101
133
  const used = usedQueryFields(query);
102
134
  const checks = [];
103
135
  const unusable = [];
104
- for (const field of ELEMENT_QUERY_FIELDS) {
136
+ // The query's own keys, not a list beside the schema. Every field here was written by the caller
137
+ // and survived parsing, so it is one the locator either consumes or drops — which is the whole
138
+ // question. Reading them off the query also means the set cannot drift from `ElementQuerySchema`.
139
+ for (const field of Object.keys(query)) {
105
140
  const want = query[field];
106
141
  if (want === undefined || used.has(field))
107
142
  continue;
@@ -14,6 +14,8 @@ 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;
19
21
  /**
@@ -29,6 +31,16 @@ export interface PredicateSession {
29
31
  * navigates simply omits it and route falls back to change-only, as before.
30
32
  */
31
33
  url?: string;
34
+ /**
35
+ * Same-origin endpoints the project DECLARED the app fires on its own — `.reticle.json`
36
+ * `background`, matched the way `urlContains` is.
37
+ *
38
+ * The settle oracle asks "has the app finished its work", and a declared telemetry endpoint that
39
+ * keeps firing answers that question with a permanent no. Excluded only when declared, because
40
+ * nothing in a URL separates the app's own telemetry from the app's work. Optional: a fake that
41
+ * omits it excludes nothing, and same-origin traffic is never guessed at.
42
+ */
43
+ background?: readonly string[] | undefined;
32
44
  /**
33
45
  * The document currently under observation, as the session derived it from its own event stream.
34
46
  *