@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,509 @@
1
+ import { ElementQuerySchema, ElementState, PredicateKind, QueryBy, } from '@reticlehq/core';
2
+ import { z } from 'zod';
3
+ import { propertyAssertionSchema } from './property.js';
4
+ /**
5
+ * Spellings an agent plausibly reaches for, mapped to the real field.
6
+ *
7
+ * `route` spells its field `pathname` while `state`, in the same union, spells its `path`. Every one
8
+ * of these was silently DROPPED before, and because these kinds have all-optional fields, dropping
9
+ * the only key supplied left a predicate that asserts nothing and passes on anything.
10
+ */
11
+ const PREDICATE_ALIASES = {
12
+ // `text`/`value` on a `text` predicate: the kind is called "text", so `text:` is the first thing
13
+ // anyone writes for it, and `value` follows from the element query's own `value` field. Both were
14
+ // hard rejections, and a rejected predicate produces NO verdict at all — the drive ends with
15
+ // nothing rather than with a failure, which is the worst outcome of the three.
16
+ [PredicateKind.TEXT]: { text: 'contains', value: 'contains' },
17
+ // `urlContains`/`url` reported from the field: an agent that had just written
18
+ // `net { urlContains }` applied the same word to `route`, which spells it `contains`, and got
19
+ // `unrecognized_keys` with no list of what would have worked. The parallel it assumed is a fair
20
+ // one — route's `contains` matches the WHOLE route (path + query + fragment), so "the URL
21
+ // contains this" is precisely what it does — and asserting a redirect after login is the single
22
+ // most common thing an agent reaches for here.
23
+ [PredicateKind.ROUTE]: { path: 'pathname', urlContains: 'contains', url: 'contains' },
24
+ [PredicateKind.NET]: { url: 'urlContains' },
25
+ // `textContains` on a `console` predicate: the reporter who hit the missing matcher reached for
26
+ // it first, by analogy with `net { urlContains }` — and that parallel is exactly right, since
27
+ // both mean "this entry must contain this substring". Accepted as an alias for `contains`.
28
+ [PredicateKind.CONSOLE]: { textContains: 'contains' },
29
+ [PredicateKind.SIGNAL]: { data: 'dataMatches' },
30
+ // `of` on a composite: it reads naturally, several assertion libraries spell it that way, and it has
31
+ // no other meaning here. Observed twice in one drive on a real app, and each rejection cost a round
32
+ // trip AND produced no verdict — a composite is what an agent reaches for precisely when it has two
33
+ // things to prove at once, so failing it is expensive at the worst moment.
34
+ [PredicateKind.ALL_OF]: { of: 'predicates' },
35
+ [PredicateKind.ANY_OF]: { of: 'predicates' },
36
+ // `of` on `not` for the same reason it is accepted on the composites above — an agent that learned
37
+ // the spelling one line earlier applies it to the third composite, and `not` was the one that
38
+ // rejected it. The refusal did name `predicate`, but naming a field still costs the round trip
39
+ // that produced no verdict, and the guess is unambiguous: `not` has exactly one child.
40
+ [PredicateKind.NOT]: { of: 'predicate' },
41
+ };
42
+ /**
43
+ * The word half the assertion world spells `kind`.
44
+ *
45
+ * A discriminated union rejects `{ type: "text", ... }` with "Invalid discriminator value" on a field
46
+ * the caller never wrote, so the reply reads as being about `kind` — which is absent — and never
47
+ * says the word `type`. Observed on a live drive as the first rung of a ladder: one field name
48
+ * learned per rejected call, each costing a verdict. No predicate kind declares a `type` field, so
49
+ * lifting it is unambiguous, and an explicit `kind` still wins.
50
+ */
51
+ const KIND_SPELLING = 'type';
52
+ /**
53
+ * Element-query fields an agent writes FLAT on an `element` predicate instead of nested under
54
+ * `query`. `reticle_query` takes exactly these at the top level, so an agent that has just located
55
+ * something writes the same words again when it asserts on it — and got `query: Required` plus an
56
+ * `unknown field` list for its trouble. Lifting them is unambiguous: they have no other meaning on
57
+ * this kind.
58
+ */
59
+ const ELEMENT_QUERY_FIELDS = [
60
+ 'by',
61
+ 'value',
62
+ 'role',
63
+ 'name',
64
+ 'text',
65
+ 'label',
66
+ 'placeholder',
67
+ 'testid',
68
+ 'alt',
69
+ 'component',
70
+ ];
71
+ /**
72
+ * The locator fields the browser actually CONSUMES for a given query — mirrors the precedence in
73
+ * `findIn` (adapters/realm/browser/src/dom/query.ts).
74
+ *
75
+ * An element query is not a conjunction. It is a first-match dispatch: `by`+`value` wins, then the
76
+ * component/source anchor, then `role` (which alone also consumes `name`), then the first of
77
+ * text/label/placeholder/testid/alt that is present. Every OTHER field the caller wrote is dropped on
78
+ * the floor, silently, and the match reported as if the whole query had been honoured.
79
+ *
80
+ * Duplicated here on purpose. The alternative is to send the question to the browser, and the browser
81
+ * cannot answer it: by the time a match comes back, the fields it ignored are indistinguishable from
82
+ * the fields it used.
83
+ */
84
+ function usedQueryFields(query) {
85
+ const used = new Set();
86
+ // The browser's `self` branch checks subtree text when supplied, but skips every other locator.
87
+ // Mark only text as consumed so role/name/etc. remain residual checks on the returned descriptor.
88
+ if (true === query.self)
89
+ return query.text === undefined ? used : used.add('text');
90
+ if (query.by !== undefined && query.value !== undefined) {
91
+ used.add('by').add('value');
92
+ if (QueryBy.ROLE === query.by)
93
+ used.add('name');
94
+ if (QueryBy.COMPONENT === query.by)
95
+ used.add('component');
96
+ return used;
97
+ }
98
+ if (query.component !== undefined || query.source !== undefined)
99
+ return used.add('component');
100
+ if (query.role !== undefined)
101
+ return used.add('role').add('name');
102
+ for (const field of ['text', 'label', 'placeholder', 'testid', 'alt']) {
103
+ if (query[field] !== undefined)
104
+ return used.add(field);
105
+ }
106
+ return used;
107
+ }
108
+ /**
109
+ * How a dropped field is checked back on the server, against the descriptor the match returned.
110
+ *
111
+ * `value` is the field this exists for: `{ role: "textbox", name: "GST amount", value: "274.58" }`
112
+ * read as a locator has no `by`, so the value half was discarded and the predicate collapsed to "a
113
+ * textbox named GST amount exists" — trivially true against an EMPTY field. Comparison is TRIMMED and
114
+ * exact: an input's value is a value, not prose, and a trailing space in either the app or the
115
+ * predicate is not a finding anybody wants. `""` asserts the field is empty, which describe() reports
116
+ * by omitting the field entirely.
117
+ *
118
+ * `role`/`name`/`value` compare against exactly what `reticle_query` REPORTS, so the words an agent
119
+ * copies out of a query result are the words that match here. `text` is a substring match, matching
120
+ * Testing Library's `exact: false`, and falls back to the name because describe() omits `text` when it
121
+ * equals the accessible name.
122
+ */
123
+ const RESIDUAL_CHECKS = {
124
+ value: (element, want) => (element.value ?? '').trim() === want.trim(),
125
+ role: (element, want) => element.role === want,
126
+ name: (element, want) => element.name.trim() === want.trim(),
127
+ text: (element, want) => (element.text ?? element.name).includes(want),
128
+ };
129
+ /**
130
+ * Split a query's dropped fields into the ones the server can still enforce and the ones it cannot.
131
+ *
132
+ * The alternative — refuse every dropped field — breaks calls that work today and that our own
133
+ * cheatsheet advertises (`{ role: "button", text: "Save" }`), and breaks them into no verdict at all.
134
+ * Enforcing what we can and refusing only the rest keeps those calls working AS WRITTEN, which is the
135
+ * outcome the caller was already assuming.
136
+ */
137
+ export function residualQueryChecks(query) {
138
+ const used = usedQueryFields(query);
139
+ const checks = [];
140
+ const unusable = [];
141
+ for (const field of ELEMENT_QUERY_FIELDS) {
142
+ const want = query[field];
143
+ if (want === undefined || used.has(field))
144
+ continue;
145
+ if ('string' === typeof want && RESIDUAL_CHECKS[field] !== undefined)
146
+ checks.push([field, want]);
147
+ else
148
+ unusable.push(field);
149
+ }
150
+ return { checks, unusable };
151
+ }
152
+ /** Does this element satisfy every field the locator dropped? */
153
+ export function satisfiesResiduals(element, checks) {
154
+ return checks.every(([field, want]) => true === RESIDUAL_CHECKS[field]?.(element, want));
155
+ }
156
+ /** How the element's own reading of a dropped field should be REPORTED back on a failure. */
157
+ export function describeResidual(element, field) {
158
+ const reading = 'value' === field
159
+ ? (element.value ?? '')
160
+ : 'text' === field
161
+ ? (element.text ?? element.name)
162
+ : 'role' === field
163
+ ? element.role
164
+ : element.name;
165
+ return `${element.role} "${element.name}" ${field}=${JSON.stringify(reading)}`;
166
+ }
167
+ /** `type` read as the discriminator when — and only when — `kind` is absent. */
168
+ function renameKindSpelling(obj) {
169
+ if (obj['kind'] !== undefined || 'string' !== typeof obj[KIND_SPELLING])
170
+ return obj;
171
+ const out = { ...obj, kind: obj[KIND_SPELLING] };
172
+ delete out[KIND_SPELLING];
173
+ return out;
174
+ }
175
+ /** Rename known aliases before parse; an explicit canonical key always wins. */
176
+ function applyPredicateAliases(input) {
177
+ if (typeof input !== 'object' || null === input || Array.isArray(input))
178
+ return input;
179
+ const given = input;
180
+ const obj = renameKindSpelling(given);
181
+ const kind = 'string' === typeof obj['kind'] ? obj['kind'] : '';
182
+ const aliases = PREDICATE_ALIASES[kind];
183
+ let out = obj;
184
+ if (aliases !== undefined) {
185
+ out = { ...obj };
186
+ for (const [from, to] of Object.entries(aliases)) {
187
+ if (out[from] === undefined)
188
+ continue;
189
+ if (out[to] === undefined)
190
+ out[to] = out[from];
191
+ delete out[from];
192
+ }
193
+ }
194
+ return PredicateKind.ELEMENT === kind ? liftElementQuery(out) : out;
195
+ }
196
+ /**
197
+ * Fold flat query fields into `query`. An explicit `query` wins outright — a caller that supplied
198
+ * both told us which one it meant, and merging the two would invent a locator neither side wrote.
199
+ */
200
+ function liftElementQuery(obj) {
201
+ const loose = ELEMENT_QUERY_FIELDS.filter((field) => obj[field] !== undefined);
202
+ if (0 === loose.length)
203
+ return obj;
204
+ const out = { ...obj };
205
+ const query = {};
206
+ for (const field of loose) {
207
+ query[field] = out[field];
208
+ delete out[field];
209
+ }
210
+ if (out['query'] === undefined)
211
+ out['query'] = query;
212
+ return out;
213
+ }
214
+ /**
215
+ * Strict on every branch. A key that is nobody's spelling is now a schema error naming it, instead of
216
+ * a stripped field and a green — see predicate-strict.test.ts for the MCP session that found this.
217
+ *
218
+ * Built on demand rather than at module scope: the `allOf`/`anyOf`/`not` branches reference
219
+ * `PredicateSchema` itself, which does not exist yet while this module is initialising. Calling it
220
+ * after init is what makes the union introspectable — see `predicateFieldsFor`.
221
+ */
222
+ function predicateUnion() {
223
+ return z.discriminatedUnion('kind', [
224
+ z
225
+ .object({
226
+ kind: z.literal(PredicateKind.ELEMENT),
227
+ query: ElementQuerySchema,
228
+ state: z.nativeEnum(ElementState).optional(),
229
+ absent: z.boolean().optional(),
230
+ })
231
+ .strict(),
232
+ z
233
+ .object({
234
+ kind: z.literal(PredicateKind.TEXT),
235
+ contains: z.string(),
236
+ visible: z.boolean().optional(),
237
+ absent: z.boolean().optional(),
238
+ scope: z.string().optional(),
239
+ self: z.boolean().optional(),
240
+ })
241
+ .strict(),
242
+ z
243
+ .object({
244
+ kind: z.literal(PredicateKind.NET),
245
+ method: z.string().optional(),
246
+ urlContains: z.string().optional(),
247
+ status: z.number().optional(),
248
+ ok: z.boolean().optional(),
249
+ since: z.number().optional(),
250
+ count: z.number().int().nonnegative().optional(),
251
+ /**
252
+ * A substring the call's RESPONSE body must contain - what the server answered.
253
+ *
254
+ * The only channel that can catch a UI echoing its own input instead of the server's answer.
255
+ * Reported from a real payments UI: a refund posted `{"amount":"1187.01"}`, the server read it
256
+ * as paise and answered 200 with `{"refunded":11.87}`, and the page displayed the number the
257
+ * user had typed. Request fired, exactly once, status 200, console clean, page settled — every
258
+ * assertable channel green on a hundred-fold wrong refund, so the verdict was `yes`.
259
+ *
260
+ * A substring rather than a JSON path, deliberately: `"refunded":11.87` is the whole assertion
261
+ * for the money case, it needs no schema for the body, and it works the same on JSON, form
262
+ * encoding and plain text. A path-and-equals form can be added later if a real case needs one;
263
+ * this is the shape that turns "a blob I read" into a verdict.
264
+ *
265
+ * Requires body capture (`reticle({ captureNetworkBodies: true })`), and says so when the body
266
+ * was never recorded rather than reporting an ordinary mismatch.
267
+ */
268
+ bodyContains: z.string().min(1).optional(),
269
+ /**
270
+ * A substring the REQUEST body must contain — the other half of `bodyContains`.
271
+ *
272
+ * `bodyContains` deliberately searches only the response, and the comment above says why:
273
+ * searching the request too would let it pass on the very defect it exists to catch. That
274
+ * reasoning is sound and it leaves a real gap. For a filter, a search or a form, the thing
275
+ * under test IS the outgoing payload: "applying this filter actually sends it" had no
276
+ * verdict at all, only `reticle_network { bodies: true }` and a human reading `requestBody`
277
+ * by eye (#798).
278
+ *
279
+ * A separate field rather than a mode on `bodyContains`, so neither assertion can ever be
280
+ * satisfied by the wrong half of the exchange.
281
+ *
282
+ * Requires body capture, and says so when the request body was never recorded rather than
283
+ * reporting an ordinary mismatch.
284
+ */
285
+ requestBodyContains: z.string().min(1).optional(),
286
+ /**
287
+ * Shallow JSON match over the REQUEST body, keyed like `signal.dataMatches` and sharing its
288
+ * `matchValue` operators (`*`, `$gte`, `$contains`, …).
289
+ *
290
+ * `{ requestBodyMatches: { filter: "manual_review" } }` is the one-call verdict for "the UI
291
+ * put the selected value into the payload", and it does not care about key order,
292
+ * whitespace or how the client serialised the object — all of which a substring does.
293
+ *
294
+ * A field whose captured value was REDACTED cannot be matched, and the verdict says so
295
+ * instead of reporting a mismatch: a redacted field is unknown, not different.
296
+ */
297
+ requestBodyMatches: z.record(z.string(), z.unknown()).optional(),
298
+ })
299
+ .strict(),
300
+ z
301
+ .object({
302
+ kind: z.literal(PredicateKind.ROUTE),
303
+ pathname: z.string().optional(),
304
+ contains: z.string().optional(),
305
+ since: z.number().optional(),
306
+ })
307
+ .strict(),
308
+ z
309
+ .object({
310
+ kind: z.literal(PredicateKind.CONSOLE),
311
+ level: z.string().optional(),
312
+ contains: z.string().min(1).optional(),
313
+ absent: z.boolean().optional(),
314
+ since: z.number().optional(),
315
+ })
316
+ .strict(),
317
+ z
318
+ .object({
319
+ kind: z.literal(PredicateKind.ANIMATION),
320
+ name: z.string().optional(),
321
+ target: z.string().optional(),
322
+ completed: z.boolean().optional(),
323
+ since: z.number().optional(),
324
+ })
325
+ .strict(),
326
+ z
327
+ .object({
328
+ kind: z.literal(PredicateKind.SIGNAL),
329
+ name: z.string().optional(),
330
+ dataMatches: z.record(z.unknown()).optional(),
331
+ /**
332
+ * Exact number of matching signals since the action — presence becomes cardinality.
333
+ *
334
+ * The double-fire is the defect no state-only oracle can see: a handler wired twice fires
335
+ * the signal twice, the store ends up in the right shape either way, and a presence check
336
+ * is green on both. The wrong-name variant is the same blind spot from the other side — the
337
+ * intended signal fires once while a mistyped sibling fires alongside it, and only a count
338
+ * scoped to the matched name tells the two apart. Omit = presence (≥1); `0` asserts the
339
+ * signal never fired, which is a claim in its own right and NOT the same as omitting it.
340
+ */
341
+ count: z.number().int().nonnegative().optional(),
342
+ since: z.number().optional(),
343
+ })
344
+ .strict(),
345
+ z
346
+ .object({
347
+ kind: z.literal(PredicateKind.STATE),
348
+ store: z.string().optional(),
349
+ path: z.string(),
350
+ equals: z.unknown().optional(),
351
+ /*
352
+ * Assert a PROPERTY instead of exact bytes, for output that is right differently every run.
353
+ * `equals` cannot express a generated summary, a classification or a computed total; this
354
+ * can, and stays decidable here with no model and no network. Supplying both is allowed and
355
+ * both must hold.
356
+ */
357
+ satisfies: propertyAssertionSchema.optional(),
358
+ })
359
+ .strict(),
360
+ z
361
+ .object({
362
+ kind: z.literal(PredicateKind.SETTLED),
363
+ quietMs: z.number().positive().optional(),
364
+ })
365
+ .strict(),
366
+ z
367
+ .object({ kind: z.literal(PredicateKind.ALL_OF), predicates: z.array(PredicateSchema) })
368
+ .strict(),
369
+ z
370
+ .object({ kind: z.literal(PredicateKind.ANY_OF), predicates: z.array(PredicateSchema) })
371
+ .strict(),
372
+ z.object({ kind: z.literal(PredicateKind.NOT), predicate: PredicateSchema }).strict(),
373
+ ]);
374
+ }
375
+ export const PredicateSchema = z.lazy(() => z.preprocess(applyPredicateAliases, predicateUnion()));
376
+ /**
377
+ * The fields a given predicate kind accepts, read off the schema itself.
378
+ *
379
+ * Derived rather than listed so the two can never disagree: a rejection message that names a stale
380
+ * field set is worse than one that names none, because the agent trusts it and retries into the same
381
+ * wall. Empty for a kind that is not in the union.
382
+ */
383
+ export function predicateFieldsFor(kind) {
384
+ const shape = shapeForKind(kind);
385
+ if (null === shape)
386
+ return [];
387
+ return Object.keys(shape).filter((field) => 'kind' !== field);
388
+ }
389
+ /**
390
+ * The union option for `kind`, or null when the kind is not one.
391
+ *
392
+ * One place that walks the union, so the field list and the nested lookup cannot disagree about
393
+ * which option a kind resolves to — and so adding a third reader is a call rather than a fourth
394
+ * copy of the same loop.
395
+ */
396
+ function shapeForKind(kind) {
397
+ for (const option of predicateUnion().options) {
398
+ const literal = option.shape['kind'];
399
+ if (literal instanceof z.ZodLiteral && literal.value === kind)
400
+ return option.shape;
401
+ }
402
+ return null;
403
+ }
404
+ /**
405
+ * Is this tool parameter ACTUALLY the predicate union?
406
+ *
407
+ * Not a name check. `until` is overloaded on this surface — the act/assert family means a predicate
408
+ * by it, while reticle_observe / _network / _console mean a NUMBER, an upper cursor bound — so any
409
+ * caller keying on the word would treat a numeric parameter as a predicate and describe it to the
410
+ * agent as an object. Keying on the schema cannot make that mistake.
411
+ *
412
+ * Lives beside the schema because two callers now ask the question: the lean tool surface, which
413
+ * compacts these parameters, and `reticle_tools`, which spells their grammar out on request. Two
414
+ * spellings of "is this a predicate" is one chance for the surface and the grammar to disagree.
415
+ */
416
+ export function isPredicateParam(schema) {
417
+ const inner = schema instanceof z.ZodOptional ? schema.unwrap() : schema;
418
+ return inner === PredicateSchema || inner === PredicateSchema.optional();
419
+ }
420
+ /**
421
+ * Every kind's fields, in one block an agent can write a predicate from.
422
+ *
423
+ * The tool surface advertises the KIND list and points at `reticle_tools` for the fields, because
424
+ * inlining the 12-variant recursive union in the declared JSON Schema costs thousands of characters
425
+ * per predicate parameter, re-sent every turn, to describe a grammar most calls use one variant of.
426
+ * That trade is right — but the pointer has to land somewhere, and it landed on a parameter
427
+ * description reading "same shape as reticle_assert". So the grammar was reachable from nothing, and
428
+ * an agent that could not find `route`'s fields fell back to a `text` check where a route check was
429
+ * meant: the weaker oracle, which is the expensive half of an undiscoverable grammar.
430
+ *
431
+ * Derived from the schema, like `predicateFieldsFor` and for the same reason: a hand-written grammar
432
+ * that drifts is worse than none, because the agent trusts it and retries into the same wall.
433
+ */
434
+ export function predicateGrammar() {
435
+ const grammar = {};
436
+ for (const kind of Object.values(PredicateKind)) {
437
+ const nested = predicateNestedFieldsFor(kind);
438
+ grammar[kind] = predicateFieldsFor(kind)
439
+ .map((field) => {
440
+ const keys = nested[field];
441
+ return undefined === keys ? field : `${field} { ${keys.join(', ')} }`;
442
+ })
443
+ .join(', ');
444
+ }
445
+ return grammar;
446
+ }
447
+ /**
448
+ * The keys of a field that is an object, once its wrappers are peeled. Empty for anything else.
449
+ *
450
+ * Exported so the wrapper handling is asserted against THIS function rather than through the
451
+ * rendered sentence. Reached only that way, a wrapper it fails to peel returns `[]`, the old
452
+ * message prints unchanged, and nothing reddens — a regression with no symptom.
453
+ *
454
+ * No top-level predicate field is currently declared behind a wrapper, so the real schema exercises
455
+ * none of these paths; that is exactly why they are worth a case each.
456
+ */
457
+ export function nestedKeysOf(schema) {
458
+ if (undefined === schema)
459
+ return [];
460
+ const inner = unwrapSchema(schema);
461
+ // `instanceof z.ZodObject` narrows to ZodObject<any>, whose `.shape` is `any`. Name the shape
462
+ // type so the keys are read off something typed rather than laundering an `any` through
463
+ // Object.keys.
464
+ if (!(inner instanceof z.ZodObject))
465
+ return [];
466
+ return Object.keys(inner.shape);
467
+ }
468
+ /** Peel optional/nullable/default/effects wrappers off a field to reach the schema underneath. */
469
+ function unwrapSchema(schema) {
470
+ let current = schema;
471
+ for (;;) {
472
+ if (current instanceof z.ZodOptional ||
473
+ current instanceof z.ZodNullable ||
474
+ current instanceof z.ZodDefault) {
475
+ current = current._def.innerType;
476
+ continue;
477
+ }
478
+ if (current instanceof z.ZodEffects) {
479
+ current = current._def.schema;
480
+ continue;
481
+ }
482
+ return current;
483
+ }
484
+ }
485
+ /**
486
+ * One level into the fields that are themselves objects — `{ query: ['by', 'value', ...] }`.
487
+ *
488
+ * Naming the top-level fields alone leaves `element` unguessable: `query` is an object with its own
489
+ * required shape, and a plain CSS string works in `reticle_snapshot.scope` and `reticle_query.scope`,
490
+ * so assuming it works here is the natural guess. The rejection is the only place that inconsistency
491
+ * can be explained.
492
+ *
493
+ * One level only. Derived from the schema for the same reason `predicateFieldsFor` is: a stale field
494
+ * list is worse than none, because the agent trusts it and retries into the same wall.
495
+ */
496
+ export function predicateNestedFieldsFor(kind) {
497
+ const shape = shapeForKind(kind);
498
+ if (null === shape)
499
+ return {};
500
+ const nested = {};
501
+ for (const [field, schema] of Object.entries(shape)) {
502
+ if ('kind' === field)
503
+ continue;
504
+ const keys = nestedKeysOf(schema);
505
+ if (0 < keys.length)
506
+ nested[field] = keys;
507
+ }
508
+ return nested;
509
+ }
@@ -0,0 +1,72 @@
1
+ import type { CommandResult, ReticleEvent } from '@reticlehq/core';
2
+ import type { KeepCallerContextFn, NoteFn } from '../../window/engine-host.js';
3
+ import type { AmbientCounts } from '../../window/ambient.js';
4
+ /**
5
+ * What the predicate engine needs from a session, and nothing more.
6
+ *
7
+ * A leaf: `predicate-element.ts` is called BY `predicate.ts` and had to import this back out of it
8
+ * just to declare its own parameter. The subset is what makes the engine testable with a fake, and a
9
+ * fake should not have to load the evaluator to be written.
10
+ */
11
+ /** The subset of Session the predicate engine needs — keeps it testable with a fake. */
12
+ export interface PredicateSession {
13
+ command(name: string, args?: Record<string, unknown>): Promise<CommandResult>;
14
+ eventsSince(cursor: number): ReticleEvent[];
15
+ onEvent(listener: (event: ReticleEvent) => void): () => void;
16
+ /** Milliseconds since connect — the same clock that stamps event `t` (injected, testable). */
17
+ elapsed(): number;
18
+ /**
19
+ * Where the app is RIGHT NOW — the session's live URL, kept current across SPA navigation.
20
+ *
21
+ * Read by the `route` predicate when the window holds no route change, which is the only way
22
+ * "did the session survive a reload?" can be answered at all. Optional: a fake session that never
23
+ * navigates simply omits it and route falls back to change-only, as before.
24
+ */
25
+ url?: string;
26
+ /**
27
+ * The document currently under observation, as the session derived it from its own event stream.
28
+ *
29
+ * Every oracle below that reads the window asks "what happened here", and a window is scoped by
30
+ * time and by ring-buffer capacity and by nothing else — so it can still hold the traffic, console
31
+ * output and signals of a page a full navigation or a reload has already thrown away. Answering a
32
+ * predicate with one of those is true about the bytes and false about the world, in whichever
33
+ * direction it lands: a stale event that satisfies the assertion is a false green, and one that
34
+ * refutes it is a false red.
35
+ *
36
+ * Optional, and undefined means nobody could say which document is current — `isSameDocument`
37
+ * treats absence as current on both sides, so the engine then behaves exactly as it did before this
38
+ * existed. Named to match `Session.currentDocumentId`, which is what supplies it in production.
39
+ */
40
+ currentDocumentId?: string | undefined;
41
+ /**
42
+ * Learned per-ref ambient-churn counts (real-time regions that churn with no action driving them).
43
+ * The settle oracle drops events on learned-ambient refs so a chat/ticker page can still go quiet.
44
+ * Optional: a session without ambient learning simply omits it and settle behaves as before.
45
+ */
46
+ ambientCounts?(): AmbientCounts;
47
+ /**
48
+ * Subscribe to session disconnect. Returns an unsubscribe function. Optional: a session without
49
+ * this hook (e.g. tests that never disconnect) simply leaves in-flight predicates until timeout.
50
+ */
51
+ onDisconnect?(listener: () => void): () => void;
52
+ /**
53
+ * True when the tab is hidden or stale enough that the browser is throttling it.
54
+ * Optional: a fake that never throttles simply omits it.
55
+ */
56
+ throttled?(): boolean;
57
+ /** Precondition failure reason (e.g. seedStorage), if any. */
58
+ preconditionFailure?(): string | undefined;
59
+ /**
60
+ * Somewhere to record a wait that could not be run at all. See engine-host.ts.
61
+ *
62
+ * Optional: a fake that omits it loses the note and nothing else. The daemon's own session
63
+ * supplies it, and `engine-host-is-supplied.test.ts` is what stops that quietly going away.
64
+ */
65
+ note?: NoteFn;
66
+ /**
67
+ * Keeps a re-check attached to the call that started the wait. See engine-host.ts.
68
+ *
69
+ * Optional: a fake that omits it gets its callback back unchanged.
70
+ */
71
+ keepCallerContext?: KeepCallerContextFn;
72
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,13 @@
1
+ import type { Predicate } from './predicate-schema.js';
2
+ import type { ExpectedLink } from '@reticlehq/core';
3
+ /**
4
+ * Convert a mustHold predicate into the ordered ExpectedLinks the divergence capsule walks. Only the
5
+ * consequence kinds (signal/net/state) become links — a presence check (element/text) can't diverge in a
6
+ * dataflow sense. allOf/anyOf flatten in order; other kinds are skipped. Pure; feeds the capsule on red.
7
+ *
8
+ * It sits with the rules rather than with the capsule because reading a declared consequence is the
9
+ * rules' own job. What it hands back is only a shape the capsule agrees to accept, and a shape costs
10
+ * nothing at run time -- it is erased when the code is built -- so the rules can still be lifted out
11
+ * on their own.
12
+ */
13
+ export declare function predicateToExpectedLinks(predicate: Predicate): ExpectedLink[];
@@ -0,0 +1,38 @@
1
+ import { ConsequenceKind, PredicateKind } from '@reticlehq/core';
2
+ /**
3
+ * Convert a mustHold predicate into the ordered ExpectedLinks the divergence capsule walks. Only the
4
+ * consequence kinds (signal/net/state) become links — a presence check (element/text) can't diverge in a
5
+ * dataflow sense. allOf/anyOf flatten in order; other kinds are skipped. Pure; feeds the capsule on red.
6
+ *
7
+ * It sits with the rules rather than with the capsule because reading a declared consequence is the
8
+ * rules' own job. What it hands back is only a shape the capsule agrees to accept, and a shape costs
9
+ * nothing at run time -- it is erased when the code is built -- so the rules can still be lifted out
10
+ * on their own.
11
+ */
12
+ export function predicateToExpectedLinks(predicate) {
13
+ switch (predicate.kind) {
14
+ case PredicateKind.SIGNAL:
15
+ return predicate.name === undefined
16
+ ? []
17
+ : [{ kind: ConsequenceKind.SIGNAL, name: predicate.name }];
18
+ case PredicateKind.NET:
19
+ return predicate.urlContains === undefined
20
+ ? []
21
+ : [
22
+ {
23
+ kind: ConsequenceKind.NET,
24
+ urlContains: predicate.urlContains,
25
+ ...(predicate.status === undefined ? {} : { status: predicate.status }),
26
+ },
27
+ ];
28
+ case PredicateKind.STATE: {
29
+ const name = predicate.store ?? predicate.path;
30
+ return [{ kind: ConsequenceKind.STATE, name }];
31
+ }
32
+ case PredicateKind.ALL_OF:
33
+ case PredicateKind.ANY_OF:
34
+ return predicate.predicates.flatMap(predicateToExpectedLinks);
35
+ default:
36
+ return [];
37
+ }
38
+ }
@@ -0,0 +1,26 @@
1
+ import { PredicateKind } from '@reticlehq/core';
2
+ import type { ExpectedLink } from '@reticlehq/core';
3
+ import { PredicateSchema, type Predicate, type EvalResult } from './predicate-eval.js';
4
+ export { PredicateSchema, PredicateKind };
5
+ export type { Predicate, EvalResult };
6
+ import type { PredicateSession } from './predicate-session.js';
7
+ export type { PredicateSession } from './predicate-session.js';
8
+ export declare function evaluatePredicate(session: PredicateSession, predicate: Predicate, since?: number, diagnose?: boolean): Promise<EvalResult>;
9
+ /**
10
+ * Evaluate now, else wait for it to become true (on each event + a poll) until timeout. `since` is
11
+ * the event-time floor (see evaluatePredicate) so a waiter cannot resolve on a stale buffered event.
12
+ */
13
+ export declare function waitForPredicate(session: PredicateSession, predicate: Predicate, timeoutMs: number, since?: number): Promise<EvalResult>;
14
+ /**
15
+ * The ExpectedLinks a GREEN verdict actually PROVED — not merely the ones it declared. Identical to
16
+ * predicateToExpectedLinks except for `anyOf`: an OR greens on a SINGLE branch, so only the branch that
17
+ * held may contribute its link. Grading a green anyOf off the declared links would let the honesty grade
18
+ * claim a signal/net consequence that was only one of the options and never fired — and a `minGrade:net`
19
+ * gate would then trust a verdict that proved nothing but presence. That is the exact false green the
20
+ * grade exists to prevent, sitting inside the grade itself.
21
+ *
22
+ * Call ONLY on a green verdict: a leaf and every `allOf` branch are returned unconditionally because a
23
+ * green top verdict guarantees they held (allOf needs all; a bare leaf IS the verdict). Only anyOf, where
24
+ * green ⇏ this-branch-held, re-checks each branch and keeps the winners.
25
+ */
26
+ export declare function provenExpectedLinks(session: PredicateSession, predicate: Predicate, since?: number): Promise<ExpectedLink[]>;