@reticlehq/engine 3.1.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 (123) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +36 -0
  3. package/dist/disagreement/body-failures.d.ts +4 -0
  4. package/dist/disagreement/body-failures.js +113 -0
  5. package/dist/disagreement/contradiction-evidence.d.ts +122 -0
  6. package/dist/disagreement/contradiction-evidence.js +194 -0
  7. package/dist/disagreement/contradiction-folds.d.ts +61 -0
  8. package/dist/disagreement/contradiction-folds.js +71 -0
  9. package/dist/disagreement/contradiction-types.d.ts +164 -0
  10. package/dist/disagreement/contradiction-types.js +1 -0
  11. package/dist/disagreement/contradictions.d.ts +5 -0
  12. package/dist/disagreement/contradictions.js +613 -0
  13. package/dist/disagreement/echo-mismatch.d.ts +10 -0
  14. package/dist/disagreement/echo-mismatch.js +299 -0
  15. package/dist/disagreement/reconcile.d.ts +39 -0
  16. package/dist/disagreement/reconcile.js +211 -0
  17. package/dist/disagreement/stale-response.d.ts +3 -0
  18. package/dist/disagreement/stale-response.js +186 -0
  19. package/dist/disagreement/unit-mismatch.d.ts +16 -0
  20. package/dist/disagreement/unit-mismatch.js +167 -0
  21. package/dist/disagreement/witness-disagreement.d.ts +42 -0
  22. package/dist/disagreement/witness-disagreement.js +43 -0
  23. package/dist/evidence/accepted-write.d.ts +35 -0
  24. package/dist/evidence/accepted-write.js +54 -0
  25. package/dist/evidence/already-true.d.ts +16 -0
  26. package/dist/evidence/already-true.js +89 -0
  27. package/dist/evidence/blind-spots.d.ts +133 -0
  28. package/dist/evidence/blind-spots.js +253 -0
  29. package/dist/evidence/body-capture-remedy.d.ts +42 -0
  30. package/dist/evidence/body-capture-remedy.js +96 -0
  31. package/dist/evidence/gap-ledger.d.ts +52 -0
  32. package/dist/evidence/gap-ledger.js +63 -0
  33. package/dist/evidence/honesty.d.ts +113 -0
  34. package/dist/evidence/honesty.js +105 -0
  35. package/dist/evidence/instrumentation-gaps.d.ts +91 -0
  36. package/dist/evidence/instrumentation-gaps.js +102 -0
  37. package/dist/evidence/learned-guards.d.ts +75 -0
  38. package/dist/evidence/learned-guards.js +78 -0
  39. package/dist/evidence/observability.d.ts +38 -0
  40. package/dist/evidence/observability.js +40 -0
  41. package/dist/evidence/page-teardown.d.ts +15 -0
  42. package/dist/evidence/page-teardown.js +17 -0
  43. package/dist/evidence/step-effect.d.ts +41 -0
  44. package/dist/evidence/step-effect.js +27 -0
  45. package/dist/evidence/uncaptured-bodies.d.ts +23 -0
  46. package/dist/evidence/uncaptured-bodies.js +41 -0
  47. package/dist/evidence/undeclared-change.d.ts +51 -0
  48. package/dist/evidence/undeclared-change.js +56 -0
  49. package/dist/evidence/unread-outcome.d.ts +10 -0
  50. package/dist/evidence/unread-outcome.js +77 -0
  51. package/dist/evidence/unsettled.d.ts +58 -0
  52. package/dist/evidence/unsettled.js +127 -0
  53. package/dist/evidence/verdict-intent-gap.d.ts +30 -0
  54. package/dist/evidence/verdict-intent-gap.js +35 -0
  55. package/dist/evidence/verified.d.ts +158 -0
  56. package/dist/evidence/verified.js +378 -0
  57. package/dist/index.d.ts +30 -0
  58. package/dist/index.js +25 -0
  59. package/dist/question/declared.d.ts +74 -0
  60. package/dist/question/declared.js +171 -0
  61. package/dist/question/lineage.d.ts +52 -0
  62. package/dist/question/lineage.js +122 -0
  63. package/dist/question/predicate/net-evidence.d.ts +21 -0
  64. package/dist/question/predicate/net-evidence.js +81 -0
  65. package/dist/question/predicate/observed-in-window.d.ts +24 -0
  66. package/dist/question/predicate/observed-in-window.js +38 -0
  67. package/dist/question/predicate/predicate-asks.d.ts +28 -0
  68. package/dist/question/predicate/predicate-asks.js +46 -0
  69. package/dist/question/predicate/predicate-console.d.ts +13 -0
  70. package/dist/question/predicate/predicate-console.js +138 -0
  71. package/dist/question/predicate/predicate-element.d.ts +13 -0
  72. package/dist/question/predicate/predicate-element.js +214 -0
  73. package/dist/question/predicate/predicate-eval-kit.d.ts +90 -0
  74. package/dist/question/predicate/predicate-eval-kit.js +126 -0
  75. package/dist/question/predicate/predicate-eval.d.ts +24 -0
  76. package/dist/question/predicate/predicate-eval.js +710 -0
  77. package/dist/question/predicate/predicate-parse.d.ts +15 -0
  78. package/dist/question/predicate/predicate-parse.js +173 -0
  79. package/dist/question/predicate/predicate-precheck.d.ts +8 -0
  80. package/dist/question/predicate/predicate-precheck.js +41 -0
  81. package/dist/question/predicate/predicate-request-body.d.ts +50 -0
  82. package/dist/question/predicate/predicate-request-body.js +120 -0
  83. package/dist/question/predicate/predicate-route.d.ts +66 -0
  84. package/dist/question/predicate/predicate-route.js +293 -0
  85. package/dist/question/predicate/predicate-schema.d.ts +170 -0
  86. package/dist/question/predicate/predicate-schema.js +509 -0
  87. package/dist/question/predicate/predicate-session.d.ts +72 -0
  88. package/dist/question/predicate/predicate-session.js +1 -0
  89. package/dist/question/predicate/predicate-to-links.d.ts +13 -0
  90. package/dist/question/predicate/predicate-to-links.js +38 -0
  91. package/dist/question/predicate/predicate.d.ts +26 -0
  92. package/dist/question/predicate/predicate.js +785 -0
  93. package/dist/question/predicate/property.d.ts +102 -0
  94. package/dist/question/predicate/property.js +135 -0
  95. package/dist/question/predicate/split-text-miss.d.ts +32 -0
  96. package/dist/question/predicate/split-text-miss.js +51 -0
  97. package/dist/question/predicate/testid-near-miss.d.ts +22 -0
  98. package/dist/question/predicate/testid-near-miss.js +33 -0
  99. package/dist/question/reaction.d.ts +17 -0
  100. package/dist/question/reaction.js +67 -0
  101. package/dist/window/adversary.d.ts +28 -0
  102. package/dist/window/adversary.js +90 -0
  103. package/dist/window/ambient.d.ts +63 -0
  104. package/dist/window/ambient.js +76 -0
  105. package/dist/window/appearance-budget.d.ts +41 -0
  106. package/dist/window/appearance-budget.js +47 -0
  107. package/dist/window/asset-noise.d.ts +42 -0
  108. package/dist/window/asset-noise.js +35 -0
  109. package/dist/window/body-relevance.d.ts +54 -0
  110. package/dist/window/body-relevance.js +78 -0
  111. package/dist/window/byte-size.d.ts +1 -0
  112. package/dist/window/byte-size.js +16 -0
  113. package/dist/window/engine-host.d.ts +35 -0
  114. package/dist/window/engine-host.js +20 -0
  115. package/dist/window/event-filters.d.ts +121 -0
  116. package/dist/window/event-filters.js +215 -0
  117. package/dist/window/json-salvage.d.ts +33 -0
  118. package/dist/window/json-salvage.js +96 -0
  119. package/dist/window/network-detail-merge.d.ts +8 -0
  120. package/dist/window/network-detail-merge.js +89 -0
  121. package/dist/window/ring-buffer.d.ts +41 -0
  122. package/dist/window/ring-buffer.js +152 -0
  123. package/package.json +71 -0
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Console predicates: the assertion agents lean on hardest, and the one with a structural blind spot.
3
+ *
4
+ * Split out of `predicate-eval.ts` when it crossed the file cap. Cohesive on its own terms — the
5
+ * level map, the channel-liveness gate, and the absent/present branches are one subject, and nothing
6
+ * else in the evaluator reads a CONSOLE_* event.
7
+ */
8
+ import { PredicateKind, type ReticleEvent } from '@reticlehq/core';
9
+ import type { EvalResult } from './predicate-eval-kit.js';
10
+ import type { Predicate } from './predicate-schema.js';
11
+ export declare function evalConsole(events: ReticleEvent[], p: Extract<Predicate, {
12
+ kind: typeof PredicateKind.CONSOLE;
13
+ }>): EvalResult;
@@ -0,0 +1,138 @@
1
+ /**
2
+ * Console predicates: the assertion agents lean on hardest, and the one with a structural blind spot.
3
+ *
4
+ * Split out of `predicate-eval.ts` when it crossed the file cap. Cohesive on its own terms — the
5
+ * level map, the channel-liveness gate, and the absent/present branches are one subject, and nothing
6
+ * else in the evaluator reads a CONSOLE_* event.
7
+ */
8
+ import { CONSOLE_ATTACH_NOTE, EventType, PredicateKind } from '@reticlehq/core';
9
+ /** The only console levels Reticle instruments (console.info/debug/trace are NOT patched). */
10
+ const CONSOLE_LEVEL_TYPE = {
11
+ log: EventType.CONSOLE_LOG,
12
+ warn: EventType.CONSOLE_WARN,
13
+ error: EventType.CONSOLE_ERROR,
14
+ };
15
+ /**
16
+ * Has the console channel reported ANYTHING in this window, at any level?
17
+ *
18
+ * Liveness, on the same argument `observerSawSubresources` makes for resource timing: one entry
19
+ * anywhere proves the channel reaches this document, so the caller is not looking at a dead read.
20
+ * Any level counts — a `console.log` proves the patch is in place just as well as an error would,
21
+ * and asking only about the ASSERTED level would re-fire the caveat on every quiet window of a
22
+ * chatty page, which is a toll paid where the warning is not true.
23
+ *
24
+ * It does not CLOSE the blind stretch — that is about time before attach and cannot be closed from
25
+ * this side. It only rules out the reading the caveat's wording would get wrong.
26
+ */
27
+ function channelReported(events, since) {
28
+ return events.some((e) => e.t >= since &&
29
+ (e.type === EventType.CONSOLE_LOG ||
30
+ e.type === EventType.CONSOLE_WARN ||
31
+ e.type === EventType.CONSOLE_ERROR ||
32
+ e.type === EventType.CONSOLE_INFO ||
33
+ e.type === EventType.CONSOLE_DEBUG ||
34
+ e.type === EventType.ERROR_UNCAUGHT));
35
+ }
36
+ export function evalConsole(events, p) {
37
+ const since = p.since ?? 0;
38
+ // Reticle only instruments console.log/warn/error. A level outside that set is never captured,
39
+ // so its events can't exist — and an `absent` assertion on it would verify NOTHING while
40
+ // reporting green. Fail loudly instead of false-passing.
41
+ if (p.level !== undefined && p.level !== 'error' && CONSOLE_LEVEL_TYPE[p.level] === undefined) {
42
+ return {
43
+ pass: false,
44
+ failureReason: `console level '${p.level}' is not captured — Reticle instruments console.log, console.warn, console.error only`,
45
+ observed: `level '${p.level}' is not instrumented, so no event of it can ever exist`,
46
+ expected: 'a level Reticle captures: log, warn, or error',
47
+ assertion: 'console.uninstrumented-level',
48
+ };
49
+ }
50
+ const matches = events.filter((e) => {
51
+ if (e.t < since)
52
+ return false;
53
+ const isErr = e.type === EventType.CONSOLE_ERROR || e.type === EventType.ERROR_UNCAUGHT;
54
+ if (p.level === undefined) {
55
+ return (e.type === EventType.CONSOLE_LOG ||
56
+ e.type === EventType.CONSOLE_WARN ||
57
+ e.type === EventType.CONSOLE_ERROR ||
58
+ e.type === EventType.ERROR_UNCAUGHT);
59
+ }
60
+ if ('error' === p.level)
61
+ return isErr;
62
+ return e.type === CONSOLE_LEVEL_TYPE[p.level];
63
+ });
64
+ // A text match narrows the population to entries whose captured message contains the substring.
65
+ // With `absent: true` this is the whole point: "THIS message did not appear", not "no messages
66
+ // appeared" — the difference between a regression check and a fragile one that any unrelated
67
+ // warning anywhere in the app breaks.
68
+ const wanted = 'contains' in p ? p.contains : undefined;
69
+ // Captured messages are strings (stringifyArgs in the browser observer), but a malformed or
70
+ // foreign event must not crash the evaluator: non-strings stringify defensively, and objects
71
+ // go through JSON.stringify rather than a default toString that would print '[object Object]'.
72
+ const asText = (v) => {
73
+ if ('string' === typeof v)
74
+ return v;
75
+ try {
76
+ return JSON.stringify(v) ?? '';
77
+ }
78
+ catch {
79
+ return '';
80
+ }
81
+ };
82
+ const matching = wanted !== undefined
83
+ ? matches.filter((e) => asText(e.data['message']).includes(wanted))
84
+ : matches;
85
+ if (true === p.absent) {
86
+ if (wanted !== undefined && 0 === matching.length && matches.length > 0) {
87
+ // Other entries exist but none carries the substring: exactly the pass an absence-with-match
88
+ // asserts. Name both counts so the caller can tell this from a silent window.
89
+ return {
90
+ pass: true,
91
+ evidence: { absent: true, contains: wanted },
92
+ };
93
+ }
94
+ return 0 === matching.length
95
+ ? {
96
+ pass: true,
97
+ evidence: {
98
+ absent: true,
99
+ // Only when the window starts at attach AND nothing came through at all. An entry
100
+ // anywhere in the window proves the channel reaches this document, which is the case
101
+ // the caveat's wording would misdescribe; a window an action opened has `since > 0` and
102
+ // was fully observed. Costs nothing on every other pass, which is most of them.
103
+ ...(0 === since && !channelReported(events, since)
104
+ ? { unobservedBefore: CONSOLE_ATTACH_NOTE }
105
+ : {}),
106
+ },
107
+ }
108
+ : {
109
+ pass: false,
110
+ failureReason: wanted !== undefined
111
+ ? `expected no ${p.level ?? 'console'} entry containing ${JSON.stringify(wanted)} but found ${String(matching.length)}`
112
+ : `expected no ${p.level ?? 'console'} entries but found ${String(matches.length)}`,
113
+ observed: wanted !== undefined
114
+ ? `${String(matching.length)} ${p.level ?? 'console'} entr${1 === matching.length ? 'y' : 'ies'} containing ${JSON.stringify(wanted)}`
115
+ : `${String(matches.length)} ${p.level ?? 'console'} entr${1 === matches.length ? 'y' : 'ies'}`,
116
+ expected: wanted !== undefined
117
+ ? `no ${p.level ?? 'console'} entry containing ${JSON.stringify(wanted)}`
118
+ : `no ${p.level ?? 'console'} entries`,
119
+ assertion: wanted !== undefined ? 'console.absent-contains' : 'console.absent',
120
+ evidence: matching.map((e) => e.data),
121
+ };
122
+ }
123
+ return matching.length > 0
124
+ ? { pass: true, evidence: matching.map((e) => e.data) }
125
+ : {
126
+ pass: false,
127
+ failureReason: wanted !== undefined
128
+ ? `no ${p.level ?? 'console'} entry containing ${JSON.stringify(wanted)} found`
129
+ : `no ${p.level ?? 'console'} entries found`,
130
+ observed: wanted !== undefined
131
+ ? `no ${p.level ?? 'console'} entry containing ${JSON.stringify(wanted)} in the window`
132
+ : `no ${p.level ?? 'console'} entries in the window`,
133
+ expected: wanted !== undefined
134
+ ? `at least one ${p.level ?? 'console'} entry containing ${JSON.stringify(wanted)}`
135
+ : `at least one ${p.level ?? 'console'} entry`,
136
+ assertion: 'console.present',
137
+ };
138
+ }
@@ -0,0 +1,13 @@
1
+ /**
2
+ * Element and text predicates: everything that resolves a locator against the live DOM.
3
+ *
4
+ * Split out of `predicate.ts` when it crossed the file cap. It is a cohesive unit on its own terms —
5
+ * one round-trip protocol (`matchOnce`), the fields the browser locator drops and this side enforces
6
+ * back (`residualQueryChecks`), the absent/present asymmetry, and the near-miss diagnostics that only
7
+ * ever enrich a failure. Nothing else in the predicate layer talks to `ReticleCommand.MATCH`.
8
+ */
9
+ import { type ElementQuery, type ElementState, type MatchResult } from '@reticlehq/core';
10
+ import { type EvalResult } from './predicate-eval.js';
11
+ import type { PredicateSession } from './predicate-session.js';
12
+ export declare function matchOnce(session: PredicateSession, query: ElementQuery, state: ElementState | undefined): Promise<MatchResult>;
13
+ export declare function evalElement(session: PredicateSession, query: ElementQuery, state: ElementState | undefined, absent: boolean, diagnose: boolean): Promise<EvalResult>;
@@ -0,0 +1,214 @@
1
+ /**
2
+ * Element and text predicates: everything that resolves a locator against the live DOM.
3
+ *
4
+ * Split out of `predicate.ts` when it crossed the file cap. It is a cohesive unit on its own terms —
5
+ * one round-trip protocol (`matchOnce`), the fields the browser locator drops and this side enforces
6
+ * back (`residualQueryChecks`), the absent/present asymmetry, and the near-miss diagnostics that only
7
+ * ever enrich a failure. Nothing else in the predicate layer talks to `ReticleCommand.MATCH`.
8
+ */
9
+ import { ReticleCommand, } from '@reticlehq/core';
10
+ import { residualQueryChecks, satisfiesResiduals, describeResidual, } from './predicate-eval.js';
11
+ import { describeTestidMiss } from './testid-near-miss.js';
12
+ import { describeSplitTextMiss } from './split-text-miss.js';
13
+ export async function matchOnce(session, query, state) {
14
+ const res = await session.command(ReticleCommand.MATCH, { query, state });
15
+ if (!res.ok)
16
+ return { matched: false, count: 0, elements: [] };
17
+ return (res.result ?? { matched: false, count: 0, elements: [] });
18
+ }
19
+ /**
20
+ * Roles that exist to ANNOUNCE something. An empty one is the container, not the message.
21
+ *
22
+ * Every toast and notification library mounts its live region at boot and never removes it, so a
23
+ * bare `{ role: "alert" }` presence check is satisfied on those apps with nothing on screen — it
24
+ * cannot fail, and a predicate that cannot fail is not a check. Restricted to these roles because
25
+ * they are the ones whose whole purpose is content: an unnamed `img`, `separator` or `progressbar`
26
+ * is an ordinary thing to assert the presence of, and is left alone.
27
+ */
28
+ const ANNOUNCEMENT_ROLES = new Set([
29
+ 'alert',
30
+ 'alertdialog',
31
+ 'status',
32
+ 'log',
33
+ 'marquee',
34
+ 'timer',
35
+ ]);
36
+ /**
37
+ * The matches that actually carry content, for a query that named none of its own.
38
+ *
39
+ * A `name`, `text` or `testid` in the query is already a specific claim and is never second-guessed
40
+ * here — this only fills the gap left by a query that asked for a role and nothing else.
41
+ */
42
+ function substantiveMatches(query, elements) {
43
+ const bareRole = query.role !== undefined &&
44
+ query.name === undefined &&
45
+ query.text === undefined &&
46
+ query.testid === undefined;
47
+ if (!bareRole || !ANNOUNCEMENT_ROLES.has(query.role ?? ''))
48
+ return elements;
49
+ // Nothing described, nothing to judge. `elements` is only the described PREFIX of a match — the
50
+ // browser truncates it, and it can be empty while `count` is not. Calling that hollow would turn a
51
+ // truncation into a verdict, so an unjudgeable set keeps the old answer.
52
+ if (0 === elements.length)
53
+ return elements;
54
+ return elements.filter((e) => e.name.length > 0 || (e.text ?? '').trim().length > 0);
55
+ }
56
+ export async function evalElement(session, query, state, absent, diagnose) {
57
+ // Fields the browser's locator would have DROPPED, enforced back here — see residualQueryChecks.
58
+ // Checked before the round-trip when nothing can enforce them: a predicate that cannot be evaluated
59
+ // must say so rather than resolve to whatever the surviving half of it happened to match.
60
+ const residual = residualQueryChecks(query);
61
+ 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';
66
+ return { pass: false, failureReason: reason, inconclusive: reason };
67
+ }
68
+ let match = await matchOnce(session, query, state);
69
+ const subject = JSON.stringify(query);
70
+ // A residual narrows the SET; `count` is every match while `elements` is only the described prefix,
71
+ // so a locator broad enough to be truncated cannot be narrowed honestly. Say so instead of guessing.
72
+ if (residual.checks.length > 0 && match.count > match.elements.length) {
73
+ const reason = `${String(match.count)} elements matched ${subject} and only ${String(match.elements.length)} were described, so ${residual.checks.map(([f]) => `\`${f}\``).join(', ')} could not be checked against all of them — narrow the locator`;
74
+ return { pass: false, failureReason: reason, inconclusive: reason };
75
+ }
76
+ const kept = match.elements.filter((element) => satisfiesResiduals(element, residual.checks));
77
+ // The locator found something and the dropped fields disagree with it. Reported separately from a
78
+ // plain miss because the fixes are opposite: the element IS there, its value is not what was claimed.
79
+ if (residual.checks.length > 0 && match.matched && 0 === kept.length && !absent) {
80
+ const wanted = residual.checks.map(([f, want]) => `${f}=${JSON.stringify(want)}`).join(', ');
81
+ return {
82
+ pass: false,
83
+ failureReason: `element matching ${subject} is present but ${wanted} does not hold`,
84
+ observed: match.elements
85
+ .map((element) => residual.checks.map(([f]) => describeResidual(element, f)).join(', '))
86
+ .join('; '),
87
+ expected: `an element matching ${subject} with ${wanted}`,
88
+ assertion: `element.${residual.checks[0]?.[0] ?? 'residual'}`,
89
+ evidence: match.elements,
90
+ };
91
+ }
92
+ if (residual.checks.length > 0) {
93
+ match = { ...match, matched: kept.length > 0, count: kept.length, elements: kept };
94
+ }
95
+ // A given-but-missing scope is handled ASYMMETRICALLY, because "absent" and "present" ask different
96
+ // questions of a scope that no longer exists:
97
+ // - ABSENT: an element is trivially absent from a container that isn't there. This is also the
98
+ // everyday "wait for the #overlay/#spinner/#modal to disappear" pattern (scope the wait to the
99
+ // node being removed) — treating scopeMissing as a hard fail there burned the whole timeout and
100
+ // flipped a correct green to red. So scopeMissing satisfies an absence check.
101
+ // - PRESENT: you cannot confirm an element is present inside a scope that resolved to nothing, and
102
+ // silently widening to the whole page is the original false green. So scopeMissing FAILS presence
103
+ // (on the wait_for path this just keeps polling until the scope appears).
104
+ if (absent) {
105
+ if (true === match.scopeMissing) {
106
+ return { pass: true, evidence: { absent: true, scopeMissing: true } };
107
+ }
108
+ return match.matched
109
+ ? {
110
+ pass: false,
111
+ failureReason: `expected element to be absent but found ${String(match.count)}`,
112
+ observed: `${String(match.count)} element(s) matching ${subject}`,
113
+ expected: `no element matching ${subject}`,
114
+ assertion: 'element.absent',
115
+ evidence: match.elements,
116
+ }
117
+ : { pass: true, evidence: { absent: true } };
118
+ }
119
+ if (true === match.scopeMissing) {
120
+ return {
121
+ pass: false,
122
+ failureReason: `scope resolved to no element — cannot confirm ${subject} is present`,
123
+ observed: 'the requested scope is not on the page (unmounted or selector matched nothing)',
124
+ expected: `an element matching ${subject} within an existing scope`,
125
+ assertion: 'element.present',
126
+ evidence: { scopeMissing: true },
127
+ };
128
+ }
129
+ const announced = substantiveMatches(query, match.elements);
130
+ if (match.matched && (announced.length > 0 || 0 === match.elements.length)) {
131
+ return { pass: true, evidence: announced };
132
+ }
133
+ // Matched, but every match was a mounted-and-empty live region. Reported as its own failure rather
134
+ // than the plain miss below, because the fixes are opposite: the container IS on the page, so
135
+ // "no element matched" would send the caller looking for a render that already happened.
136
+ if (match.matched) {
137
+ return {
138
+ pass: false,
139
+ failureReason: `${String(match.count)} element(s) matched ${subject}, and every one is empty — ` +
140
+ 'a live region mounted with no name and no text has announced nothing. Assert the ' +
141
+ 'message itself (a `name` or `text` in the query) rather than the container',
142
+ observed: `${String(match.count)} empty '${query.role ?? ''}' region(s) with no name or text`,
143
+ expected: `a '${query.role ?? ''}' carrying a name or rendered text`,
144
+ assertion: 'element.announced',
145
+ evidence: match.elements,
146
+ };
147
+ }
148
+ // The near-miss diagnostic below costs one or two EXTRA MATCH round-trips. It only enriches a FAILED
149
+ // verdict, and a wait loop's interim rechecks read nothing but `pass` — so on the poll path (diagnose
150
+ // false) skip straight to the plain fail. Under an event flood a role+name element wait was firing
151
+ // two live-DOM scans per recheck for a diagnostic no interim eval ever reads; the final timeout eval
152
+ // still runs with diagnose=true and produces the full near-miss.
153
+ if (!diagnose) {
154
+ return {
155
+ pass: false,
156
+ failureReason: `no element matched ${subject}${state === undefined ? '' : ` in state '${state}'`}`,
157
+ observed: 'no matching element on the page',
158
+ expected: `an element matching ${subject}${state === undefined ? '' : ` in state '${state}'`}`,
159
+ assertion: 'element.present',
160
+ };
161
+ }
162
+ // Diagnostic near-miss: was it there but in the wrong state, or a similar element present?
163
+ if (state !== undefined) {
164
+ const relaxed = await matchOnce(session, query, undefined);
165
+ if (relaxed.matched) {
166
+ return {
167
+ pass: false,
168
+ failureReason: `element exists but not in state '${state}'`,
169
+ observed: `element matching ${subject} is present, states: ${relaxed.elements[0]?.states.join(', ') ?? 'unknown'}`,
170
+ expected: `element matching ${subject} in state '${state}'`,
171
+ assertion: 'element.state',
172
+ evidence: { nearMiss: relaxed.elements },
173
+ };
174
+ }
175
+ }
176
+ if (query.role !== undefined && query.name !== undefined) {
177
+ const roleOnly = await matchOnce(session, { role: query.role }, state);
178
+ if (roleOnly.matched) {
179
+ return {
180
+ pass: false,
181
+ failureReason: `no '${query.role}' named '${query.name}'; saw: ${roleOnly.elements
182
+ .map((e) => e.name)
183
+ .filter((n) => n.length > 0)
184
+ .join(', ')}`,
185
+ observed: `${String(roleOnly.count)} '${query.role}' element(s), named: ${roleOnly.elements
186
+ .map((e) => e.name)
187
+ .filter((n) => n.length > 0)
188
+ .join(', ')}`,
189
+ expected: `a '${query.role}' named '${query.name}'`,
190
+ assertion: 'element.role+name',
191
+ evidence: { nearMiss: roleOnly.elements },
192
+ };
193
+ }
194
+ }
195
+ // The testid near-miss: name what IS here, so a typo is one step from fixed rather than a dead
196
+ // end. reticle_query has always done this; the predicate path had no equivalent. See
197
+ // testid-near-miss.ts.
198
+ const present = match.hint?.presentTestids ?? [];
199
+ const alsoHere = query.testid === undefined ? undefined : describeTestidMiss(query.testid, present);
200
+ // A text miss where the string is on the page but split across children reads exactly like an
201
+ // element that never rendered. Naming the container is the difference between a retry and a bug
202
+ // report against working code. See split-text-miss.ts.
203
+ const splitText = describeSplitTextMiss(match.hint?.splitText, query.text);
204
+ const clause = splitText ?? (alsoHere === undefined || '' === alsoHere ? undefined : alsoHere);
205
+ const suffix = clause === undefined ? '' : ` — ${clause}`;
206
+ return {
207
+ pass: false,
208
+ failureReason: `no element matched ${subject}${state === undefined ? '' : ` in state '${state}'`}${suffix}`,
209
+ observed: `no matching element on the page${suffix}`,
210
+ expected: `an element matching ${subject}${state === undefined ? '' : ` in state '${state}'`}`,
211
+ assertion: 'element.present',
212
+ ...(present.length > 0 ? { evidence: { presentTestids: present } } : {}),
213
+ };
214
+ }
@@ -0,0 +1,90 @@
1
+ import { PredicateKind } from '@reticlehq/core';
2
+ import type { Predicate } from './predicate-schema.js';
3
+ /**
4
+ * What an evaluation ANSWERS, and the small comparisons every oracle answers it with.
5
+ *
6
+ * A leaf. `predicate-console.ts` and `predicate-request-body.ts` are called BY `predicate-eval.ts`
7
+ * and both had to import back out of it — the result type to declare their own signatures, and four
8
+ * comparison helpers to do the comparing. Nothing here reads an event or decides a verdict; it is
9
+ * the vocabulary those decisions are written in, which is why it can sit underneath all of them.
10
+ */
11
+ export interface EvalResult {
12
+ pass: boolean;
13
+ /**
14
+ * For a TIME-based failure: how long until this predicate could first become true, if nothing else
15
+ * changes. Purely a scheduling hint for `waitForPredicate` — it replaces a blind poll tick with one
16
+ * timed to the moment that matters, and never decides anything. Absent when the wait is on an
17
+ * external event (a request in flight settles when the server answers, not on a clock).
18
+ */
19
+ retryAfterMs?: number;
20
+ /**
21
+ * Set when the assertion could not be EVALUATED — the call was under-specified or there was
22
+ * nothing instrumented to read — rather than evaluated and found false. Carries the sentence that
23
+ * names what is missing.
24
+ *
25
+ * `pass` stays false because nothing was proven, but a false that nobody could have made true is
26
+ * not a defect in the user's app, and reporting it as one puts agent mistakes into the bug count.
27
+ */
28
+ inconclusive?: string;
29
+ /**
30
+ * No later event in this window can change this answer, so waiting out the rest of the budget
31
+ * buys nothing.
32
+ *
33
+ * Set ONLY where that is provable, which is rarer than it looks. "The toast never appeared" is not
34
+ * decided — it is only knowable when the budget ends, and ending early there would manufacture the
35
+ * false negative the budget exists to prevent. Exact cardinality IS decided once exceeded, because
36
+ * a window only accumulates matches and a count cannot come back down.
37
+ *
38
+ * A scheduling fact, never a verdict: `pass` already says what the answer is, and this only says
39
+ * that it is final.
40
+ */
41
+ decided?: boolean;
42
+ evidence?: unknown;
43
+ failureReason?: string;
44
+ /**
45
+ * The wait ended because the TAB went away, not because the app did anything observable.
46
+ *
47
+ * A sibling of `inconclusive` and for the same reason: `pass` is false because nothing was
48
+ * proven, but nobody could have made it true, so grading it as a defect in the user's app is a
49
+ * false claim. Without this the verdict rule saw only `pass: false` and answered
50
+ * `assertion_failed` — "the declared consequence did not hold" — naming the component the agent
51
+ * had just clicked. See VerifiedReason.OBSERVATION_LOST.
52
+ */
53
+ observationLost?: boolean;
54
+ /**
55
+ * The failure, structured — what was seen, what was required, and which oracle judged it.
56
+ *
57
+ * `failureReason` says the same thing in prose, and prose is the WRONG shape for this: measured on
58
+ * three seeded bugs, an agent handed observed/expected/assertion alongside the source pointer used
59
+ * fewer tool calls than one handed the pointer alone, and the repair literature has structured
60
+ * feedback beating rich natural-language feedback by 10.5pp. The prose stays for humans reading a
61
+ * log; these three fields are for the agent.
62
+ *
63
+ * Optional because they are populated per oracle, not globally — see the note in predicate.ts on
64
+ * which classes carry them today.
65
+ */
66
+ observed?: string;
67
+ expected?: string;
68
+ assertion?: string;
69
+ }
70
+ export declare function str(value: unknown): string | undefined;
71
+ export declare function num(value: unknown): number | undefined;
72
+ /**
73
+ * Match one value against a pattern. Supports `*` (present), strict equality, and operators:
74
+ * `{$gte,$lte,$gt,$lt}` (numbers), `{$contains}` (array membership or substring), `{$length}`.
75
+ */
76
+ export declare function matchValue(got: unknown, want: unknown): boolean;
77
+ /** Shallow JSON pattern match: each key in `pattern` must match (see matchValue). */
78
+ export declare function dataMatches(actual: Record<string, unknown>, pattern: Record<string, unknown>): boolean;
79
+ /** Enough of a body to see what differed, without paying for a whole payload in the verdict. */
80
+ export declare function clipBody(body: string): string;
81
+ /**
82
+ * The filter as APPLIED, every field of it.
83
+ *
84
+ * The count failure used to print `{method, urlContains, status}` while `ok` and `bodyContains` were
85
+ * applied too, so the caller was shown a predicate it had not written and told nothing matched it.
86
+ * A printed filter that is narrower than the real one is worse than none: it is believed.
87
+ */
88
+ export declare function describeNetFilter(p: Extract<Predicate, {
89
+ kind: typeof PredicateKind.NET;
90
+ }>): string;
@@ -0,0 +1,126 @@
1
+ import { PredicateKind } from '@reticlehq/core';
2
+ export function str(value) {
3
+ return 'string' === typeof value ? value : undefined;
4
+ }
5
+ export function num(value) {
6
+ return 'number' === typeof value ? value : undefined;
7
+ }
8
+ /**
9
+ * Match one value against a pattern. Supports `*` (present), strict equality, and operators:
10
+ * `{$gte,$lte,$gt,$lt}` (numbers), `{$contains}` (array membership or substring), `{$length}`.
11
+ */
12
+ export function matchValue(got, want) {
13
+ if ('*' === want)
14
+ return got !== undefined;
15
+ // An object is an OPERATOR container only if it actually carries a `$`-prefixed operator. An empty
16
+ // `{}` (or an object with no `$` key) used to enter this branch, iterate zero recognized operators,
17
+ // and `return true` — so `equals: {}` / `dataMatches: {status: {}}` was a green assertion that
18
+ // passed against ANYTHING, undefined included: the exact false green the oracle exists to catch.
19
+ // Without an operator it is a literal to compare, and falls through to strict equality below.
20
+ const ops = 'object' === typeof want && want !== null && !Array.isArray(want)
21
+ ? Object.entries(want)
22
+ : undefined;
23
+ if (ops !== undefined && ops.some(([op]) => op.startsWith('$'))) {
24
+ for (const [op, val] of ops) {
25
+ const n = 'number' === typeof got ? got : NaN;
26
+ switch (op) {
27
+ case '$gte':
28
+ if (!(n >= val))
29
+ return false;
30
+ break;
31
+ case '$lte':
32
+ if (!(n <= val))
33
+ return false;
34
+ break;
35
+ case '$gt':
36
+ if (!(n > val))
37
+ return false;
38
+ break;
39
+ case '$lt':
40
+ if (!(n < val))
41
+ return false;
42
+ break;
43
+ case '$contains':
44
+ if (Array.isArray(got)) {
45
+ if (!got.includes(val))
46
+ return false;
47
+ }
48
+ else if ('string' === typeof got) {
49
+ if (!got.includes(String(val)))
50
+ return false;
51
+ }
52
+ else {
53
+ return false;
54
+ }
55
+ break;
56
+ case '$length':
57
+ if (!((Array.isArray(got) || 'string' === typeof got) && got.length === val)) {
58
+ return false;
59
+ }
60
+ break;
61
+ default:
62
+ return false;
63
+ }
64
+ }
65
+ return true;
66
+ }
67
+ return structurallyEqual(got, want);
68
+ }
69
+ /**
70
+ * Value equality for the leaf comparison, because `===` could never match a literal.
71
+ *
72
+ * The expected side of a predicate is parsed out of the agent's JSON, so it is a fresh object every
73
+ * time — reference equality made `equals: ["a", "b"]` false against a store holding exactly
74
+ * `["a", "b"]`, and there was no value of the app's state that could have made it true. The mirror of
75
+ * a false green: an assertion nobody could satisfy, on the commonest thing there is to assert about.
76
+ *
77
+ * Deliberately strict about shape. An array is not an object, an extra key is a difference, and order
78
+ * is part of a list's value — `equals` means equals; `dataMatches` is the field-by-field one.
79
+ */
80
+ function structurallyEqual(got, want) {
81
+ if (got === want)
82
+ return true;
83
+ if (null === got || null === want)
84
+ return false;
85
+ if ('object' !== typeof got || 'object' !== typeof want)
86
+ return false;
87
+ if (Array.isArray(got) !== Array.isArray(want))
88
+ return false;
89
+ if (Array.isArray(got) && Array.isArray(want)) {
90
+ return got.length === want.length && got.every((v, i) => structurallyEqual(v, want[i]));
91
+ }
92
+ const a = got;
93
+ const b = want;
94
+ const keys = Object.keys(a);
95
+ if (keys.length !== Object.keys(b).length)
96
+ return false;
97
+ return keys.every((k) => k in b && structurallyEqual(a[k], b[k]));
98
+ }
99
+ /** Shallow JSON pattern match: each key in `pattern` must match (see matchValue). */
100
+ export function dataMatches(actual, pattern) {
101
+ for (const [key, want] of Object.entries(pattern)) {
102
+ if (!matchValue(actual[key], want))
103
+ return false;
104
+ }
105
+ return true;
106
+ }
107
+ /**
108
+ * How much of a response body a failure may quote. Enough to see the value that differed on the
109
+ * bodies this field is used against (a JSON answer), and not a whole payload in every verdict.
110
+ */
111
+ const MAX_BODY_IN_FAILURE = 200;
112
+ /** Enough of a body to see what differed, without paying for a whole payload in the verdict. */
113
+ export function clipBody(body) {
114
+ return body.length <= MAX_BODY_IN_FAILURE ? body : `${body.slice(0, MAX_BODY_IN_FAILURE)}…`;
115
+ }
116
+ /**
117
+ * The filter as APPLIED, every field of it.
118
+ *
119
+ * The count failure used to print `{method, urlContains, status}` while `ok` and `bodyContains` were
120
+ * applied too, so the caller was shown a predicate it had not written and told nothing matched it.
121
+ * A printed filter that is narrower than the real one is worse than none: it is believed.
122
+ */
123
+ export function describeNetFilter(p) {
124
+ const { kind: _kind, count: _count, since: _since, ...filter } = p;
125
+ return JSON.stringify(filter);
126
+ }
@@ -0,0 +1,24 @@
1
+ import { PredicateKind, type ReticleEvent } from '@reticlehq/core';
2
+ export { evalConsole } from './predicate-console.js';
3
+ import type { Predicate } from './predicate-schema.js';
4
+ import { type EvalResult } from './predicate-eval-kit.js';
5
+ export { clipBody, dataMatches, describeNetFilter, matchValue, str, type EvalResult, } from './predicate-eval-kit.js';
6
+ export * from './predicate-schema.js';
7
+ export declare function evalNet(events: ReticleEvent[], p: Extract<Predicate, {
8
+ kind: typeof PredicateKind.NET;
9
+ }>): EvalResult;
10
+ export declare function evalAnimation(events: ReticleEvent[], p: Extract<Predicate, {
11
+ kind: typeof PredicateKind.ANIMATION;
12
+ }>): EvalResult;
13
+ export declare function evalSignal(events: ReticleEvent[], p: Extract<Predicate, {
14
+ kind: typeof PredicateKind.SIGNAL;
15
+ }>): EvalResult;
16
+ /**
17
+ * "The page has gone quiet": no network/DOM/animation activity for at least `quietMs`. Needs the
18
+ * wall-clock `now` (in the buffer's time base) because "no activity in the last N ms" is relative to
19
+ * now, not to any buffered event — so `now` is injected (CLAUDE.md rule 7), and the wait loop's
20
+ * poll interval is what eventually flips this to pass once activity stops.
21
+ */
22
+ export declare function evalSettled(allEvents: ReticleEvent[], p: Extract<Predicate, {
23
+ kind: typeof PredicateKind.SETTLED;
24
+ }>, now: number): EvalResult;