@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,710 @@
1
+ import { EventType, PredicateKind, StreamDirection, isDevToolingUrl, urlForMatch, REDACTED_VALUE, } from '@reticlehq/core';
2
+ import { describeObserved } from './observed-in-window.js';
3
+ import { netEvidence } from './net-evidence.js';
4
+ import { checkRequestBody, newRequestBodyState, requestBodyVerdict, } from './predicate-request-body.js';
5
+ export { evalConsole } from './predicate-console.js';
6
+ import { clipBody, dataMatches, describeNetFilter, num, str, } from './predicate-eval-kit.js';
7
+ export { clipBody, dataMatches, describeNetFilter, matchValue, str, } from './predicate-eval-kit.js';
8
+ // The predicate SHAPE — the discriminated union, its aliases and its zod schema — lives in
9
+ // predicate-schema.ts, and is re-exported here: the two halves are ONE public surface.
10
+ export * from './predicate-schema.js';
11
+ /**
12
+ * Did this call succeed, as the app experienced it?
13
+ *
14
+ * `ok` is authoritative when present — IPC sets it explicitly, because an IPC call has no status
15
+ * code and the 200/500 Reticle derives is a convenience, not a fact. Falling back to the HTTP status
16
+ * keeps ordinary web requests working without the observer having to set the field everywhere.
17
+ *
18
+ * This exists so an agent can assert on the OUTCOME rather than on a number Reticle invented.
19
+ */
20
+ function callSucceeded(data) {
21
+ if ('boolean' === typeof data['ok'])
22
+ return data['ok'];
23
+ const status = num(data['status']);
24
+ return status === undefined || status < 400;
25
+ }
26
+ /**
27
+ * One call, as the failure report should name it: `POST /api/generate-script → 500`.
28
+ *
29
+ * The status used to be dropped here, which made the most common net failure unreadable. Asserting
30
+ * `{status: 200}` against a call that returned 500 reported only `POST /api/generate-script` — the
31
+ * very field the predicate filtered on was missing from the account of what was seen, so the agent
32
+ * is told the call happened and left to guess why it did not match.
33
+ *
34
+ * The arrow is OMITTED when there is no status. An in-flight or aborted request genuinely has none,
35
+ * and `→ undefined` would be a fabricated fact about the wire.
36
+ */
37
+ function describeCall(e) {
38
+ const head = `${str(e.data['method']) ?? 'GET'} ${str(e.data['url']) ?? ''}`;
39
+ const status = num(e.data['status']);
40
+ return status === undefined ? head : `${head} → ${String(status)}`;
41
+ }
42
+ /**
43
+ * What a miss should say when the displayed URL was redacted. Matching uses `urlRaw` when present;
44
+ * an older SDK has no copy, so the miss has to say which of the two it is.
45
+ */
46
+ const REDACTED_PATH_HINT = 'this path segment was redacted — the literal you matched may be here, try bodyContains';
47
+ function observedNetCalls(events, urlContains) {
48
+ const calls = events.filter((e) => e.type === EventType.NET_REQUEST);
49
+ const base = describeObserved('calls', calls.map(describeCall));
50
+ if (urlContains === undefined)
51
+ return base;
52
+ const encoded = encodeURIComponent(REDACTED_VALUE);
53
+ const redacted = calls.some((e) => {
54
+ const url = str(e.data['url']) ?? '';
55
+ return url.includes(REDACTED_VALUE) || url.includes(encoded);
56
+ });
57
+ return redacted ? `${base}; ${REDACTED_PATH_HINT}` : base;
58
+ }
59
+ /** Same, for a signal: the matcher as applied, with the cardinality and the floor taken out. */
60
+ function describeSignalFilter(p) {
61
+ const { kind: _kind, count: _count, since: _since, ...filter } = p;
62
+ return JSON.stringify(filter);
63
+ }
64
+ /**
65
+ * Exact cardinality, once, for every channel that can count its matches.
66
+ *
67
+ * `net` and `signal` are the same assertion over different evidence — "this happened EXACTLY n
68
+ * times" — and the interesting half is the same on both: an over-count is `decided`, because a
69
+ * window only accumulates and a count cannot come back down, so waiting out the rest of the budget
70
+ * to report a double-fire buys nothing but latency.
71
+ *
72
+ * `noun` names the population in prose ("network call(s)", "signal(s)"), `filter` is the matcher as
73
+ * applied, and `assertion` is the oracle that judged it.
74
+ */
75
+ function evalExactCount(args) {
76
+ const { matched, want, noun, filter, assertion } = args;
77
+ if (matched === want)
78
+ return { pass: true, evidence: { matched } };
79
+ return {
80
+ pass: false,
81
+ ...(matched > want ? { decided: true } : {}),
82
+ failureReason: `expected ${String(want)} ${noun} matching ${filter}, saw ${String(matched)}`,
83
+ observed: `${String(matched)} matching ${noun}`,
84
+ expected: `exactly ${String(want)} matching ${filter}`,
85
+ assertion,
86
+ };
87
+ }
88
+ /**
89
+ * URL suffixes only the DOCUMENT fetches, which the network observer therefore never records.
90
+ *
91
+ * `network.ts` patches `fetch` and `XMLHttpRequest` and nothing else, so `<link rel=icon>`,
92
+ * `<link rel=manifest>`, stylesheets, fonts and `<img src>` are invisible to it. "No matching call"
93
+ * and "that class of call is not observed" are then indistinguishable, and the miss graded
94
+ * `assertion_failed` — a false RED. Reported from the field: an assert over `/favicon.ico`,
95
+ * `/site.webmanifest` and `/apple-touch-icon.png` returned `verified:"no"` while curl showed all
96
+ * three answering 200. A false negative here is worse than an unknown, because an agent that trusts
97
+ * it goes and "fixes" working code.
98
+ *
99
+ * Deliberately NOT here: `.js` and `.json`. Both are routinely fetched via `fetch`/XHR — a module
100
+ * preload and an API call can share a suffix — so downgrading them would hide real misses. This list
101
+ * is only the suffixes for which the document is the sole plausible initiator.
102
+ *
103
+ * This began as the smaller half of #447: it did not make these requests observable, it stopped
104
+ * Reticle claiming they did not happen. The other half, observing them via resource timing, has
105
+ * since landed in the browser SDK, so the two halves are no longer independent and this downgrade is
106
+ * now GATED: when the event stream carries at least one document-initiated record, the observer is
107
+ * demonstrably live and a miss over these suffixes is real evidence, graded a plain failure. Only a
108
+ * page whose stream holds no resource entry at all keeps the honest "cannot tell apart" answer,
109
+ * because there the observer may simply not exist.
110
+ */
111
+ const DOCUMENT_ONLY_SUFFIXES = [
112
+ '.ico',
113
+ '.png',
114
+ '.jpg',
115
+ '.jpeg',
116
+ '.gif',
117
+ '.svg',
118
+ '.webp',
119
+ '.avif',
120
+ '.bmp',
121
+ '.css',
122
+ '.woff',
123
+ '.woff2',
124
+ '.ttf',
125
+ '.otf',
126
+ '.eot',
127
+ '.webmanifest',
128
+ ];
129
+ /**
130
+ * File suffixes a click typically downloads or navigates to as a document, never as fetch/XHR.
131
+ *
132
+ * Sibling of DOCUMENT_ONLY_SUFFIXES, not a member of it. Those are subresources: once resource
133
+ * timing is live, a miss is evidence. A click on `<a href="/export.pdf">` is a navigation (or a
134
+ * Content-Disposition attachment). Resource timing of stylesheets does not make it visible, so
135
+ * grading the miss as "0 network calls" / a 404 is the lie #805 exists to stop — even on a page
136
+ * whose observer is running. `.js` / `.json` stay off this list for the same reason they stay off
137
+ * the other: they are routinely fetched.
138
+ */
139
+ const NATIVE_DOWNLOAD_SUFFIXES = [
140
+ '.pdf',
141
+ '.csv',
142
+ '.tsv',
143
+ '.zip',
144
+ '.gz',
145
+ '.tar',
146
+ '.xlsx',
147
+ '.xls',
148
+ '.docx',
149
+ '.doc',
150
+ '.pptx',
151
+ '.ppt',
152
+ '.ods',
153
+ '.odt',
154
+ '.rtf',
155
+ '.7z',
156
+ '.rar',
157
+ ];
158
+ /**
159
+ * Does this filter target a class of request the observer cannot see?
160
+ *
161
+ * Read off `urlContains` only, and only when the pattern ENDS in one of the suffixes — a filter of
162
+ * `/api/` that happens to contain `.css` somewhere in a query string is still an ordinary XHR
163
+ * target. Query strings and fragments are stripped first, since `favicon.ico?v=2` is the same asset.
164
+ */
165
+ function filterPath(urlContains) {
166
+ return (urlContains.split('#')[0] ?? '').split('?')[0]?.toLowerCase() ?? '';
167
+ }
168
+ /**
169
+ * Does this filter target a class of request the observer cannot see?
170
+ *
171
+ * Read off `urlContains` only, and only when the pattern ENDS in one of the suffixes — a filter of
172
+ * `/api/` that happens to contain `.css` somewhere in a query string is still an ordinary XHR
173
+ * target. Query strings and fragments are stripped first, since `favicon.ico?v=2` is the same asset.
174
+ */
175
+ function targetsUnobservedChannel(p) {
176
+ const url = p.urlContains;
177
+ if (undefined === url)
178
+ return false;
179
+ return DOCUMENT_ONLY_SUFFIXES.some((suffix) => filterPath(url).endsWith(suffix));
180
+ }
181
+ function targetsNativeDownload(p) {
182
+ const url = p.urlContains;
183
+ if (undefined === url)
184
+ return false;
185
+ return NATIVE_DOWNLOAD_SUFFIXES.some((suffix) => filterPath(url).endsWith(suffix));
186
+ }
187
+ function nativeDownloadReason(p) {
188
+ return (`no fetch or XHR matched ${describeNetFilter(p)}. A native download or document navigation ` +
189
+ `(an <a href> to a file, a Content-Disposition attachment, <a download>) never goes through ` +
190
+ `fetch or XMLHttpRequest, so an empty net window is not a 404 and is not evidence the export ` +
191
+ `failed. This is unobservable on the net channel. Assert the link href, or check the file ` +
192
+ `outside the browser — Reticle cannot see the bytes land`);
193
+ }
194
+ function nativeDownloadMiss(events, p) {
195
+ if (!targetsNativeDownload(p))
196
+ return undefined;
197
+ const reason = nativeDownloadReason(p);
198
+ return {
199
+ pass: false,
200
+ failureReason: reason,
201
+ inconclusive: reason,
202
+ observed: observedNetCalls(events, p.urlContains),
203
+ expected: `a fetch or XHR matching ${describeNetFilter(p)}`,
204
+ assertion: 'net.native-download',
205
+ };
206
+ }
207
+ /**
208
+ * Initiator types the browser SDK's resource-timing observer stamps onto document-initiated records
209
+ * (adapters/realm/browser/src/observers/network.ts). The patched transports sign themselves `fetch`,
210
+ * `xhr` or `beacon`, so any NET_REQUEST carrying one of these came from a `resource` entry, and its
211
+ * mere presence is proof the PerformanceObserver is alive on this page. Mirrors the wire; keep in
212
+ * sync with the browser package.
213
+ */
214
+ const DOCUMENT_INITIATORS = new Set([
215
+ 'link',
216
+ 'css',
217
+ 'img',
218
+ 'script',
219
+ 'manifest',
220
+ 'other',
221
+ ]);
222
+ /**
223
+ * Did the observer actually report a document-initiated load?
224
+ *
225
+ * This is the gate on the unobserved-channel downgrade above. Once subresource observation landed,
226
+ * a miss over `.ico`/`.css`/`.woff2` is no longer inherently unknowable: if the observer is live it
227
+ * would have seen the favicon load, so seeing none is evidence it never fired. But the observer is
228
+ * opt-in-by-engine, not guaranteed: on a renderer without `PerformanceObserver` (or before any
229
+ * resource entry exists) nothing distinguishes "not requested" from "not visible", and the honest
230
+ * answer stays inconclusive. Liveness is inferred from the same events being judged: one
231
+ * document-initiated record anywhere in the window proves the channel works.
232
+ */
233
+ function observerSawSubresources(events) {
234
+ return events.some((e) => {
235
+ if (e.type !== EventType.NET_REQUEST)
236
+ return false;
237
+ const initiator = str(e.data['initiator']);
238
+ return initiator !== undefined && DOCUMENT_INITIATORS.has(initiator);
239
+ });
240
+ }
241
+ /** The sentence both zero-match branches hand to `inconclusive`. */
242
+ function unobservedChannelReason(p) {
243
+ return (`no call matched ${describeNetFilter(p)}, and no document-initiated load was recorded either, ` +
244
+ `so this page exposed no resource timing to read: Reticle observes fetch and XMLHttpRequest ` +
245
+ `directly, while a request the document initiates (<link rel=icon|manifest|preload>, a ` +
246
+ `stylesheet, a font, <img src>) leaves no record, and that state cannot be told apart from the ` +
247
+ `request having been made. ` +
248
+ `Nothing here says the app is wrong. Check it outside the browser, or assert something the ` +
249
+ `document does not fetch on its own`);
250
+ }
251
+ /**
252
+ * Appended to a zero-match `net` negative whose window starts at SDK attach.
253
+ *
254
+ * Every event's `t` is stamped `performance.now() - #start`, where `#start` is taken when the SDK
255
+ * is constructed, so `t` is never negative and a window with `since === 0` begins AT attach — never
256
+ * before it. Whatever the page did between navigation start and attach left no event at all, so
257
+ * "no matching call" over such a window cannot be told apart from "the call was made while nothing
258
+ * was watching yet".
259
+ *
260
+ * The gap is routine rather than exotic: a `fetch` from an effect in a root provider, or a classic
261
+ * `<script>` at the end of `<body>`, fires before a deferred module script has run. Read as proof
262
+ * the request was never made, that sends a reader looking for a defect in code that works —
263
+ * restarting dev servers and re-reading providers to establish that the request was invisible rather
264
+ * than absent.
265
+ *
266
+ * Same argument as DOCUMENT_ONLY_SUFFIXES one axis over: that one is a channel Reticle does not
267
+ * watch, this is a stretch of TIME it was not yet watching.
268
+ *
269
+ * The grade is deliberately NOT downgraded to `inconclusive`. A missing API call is the finding this
270
+ * oracle exists to make, and it is the strongest grade available for the startup class — session
271
+ * restore, feature flags, bootstrap config — which is exactly the class that silently breaks on
272
+ * reload. Every window an action opens carries `since > 0` and is untouched. What changes is only
273
+ * what the negative CLAIMS: it stops asserting the request never happened, and names the assertion
274
+ * that can settle it, because the state such a request produces IS observable after attach.
275
+ */
276
+ const PRE_ATTACH_CAVEAT = ' — note that this window starts where the SDK attached, and requests made before that are never ' +
277
+ 'captured, so a miss here cannot tell a call that was never made apart from one made before the ' +
278
+ 'page connected; if the call is expected during startup, assert on the state it produces instead';
279
+ export function evalNet(events, p) {
280
+ const since = p.since ?? 0;
281
+ /**
282
+ * Computed once: the gate every zero-match downgrade below reads. True means the resource-timing
283
+ * observer is demonstrably live in this window, so a miss is evidence rather than blindness.
284
+ */
285
+ const sawSubresources = observerSawSubresources(events);
286
+ /**
287
+ * Did any call match everything EXCEPT the body assertion, while carrying no recorded body?
288
+ *
289
+ * Bodies are opt-in, so without them a body predicate can never hold — and "no call matched" would
290
+ * send the caller to check the url and the method, which are both fine, instead of to the one
291
+ * setting that makes the assertion possible. Tracked while filtering rather than recomputed after,
292
+ * because it is the same pass over the same events.
293
+ */
294
+ let matchedButUnrecorded = false;
295
+ /** A call matched url/method but carried NO readable status (document-initiated subresource). */
296
+ let unobservableStatus = false;
297
+ /**
298
+ * The response body of a call that matched everything EXCEPT the body assertion, and HAD one.
299
+ *
300
+ * Reported by the first field user of `bodyContains`: a body mismatch was formatted as
301
+ * "expected 1 network call(s) matching {method, urlContains, status}, saw 0" — the body assertion
302
+ * was applied but not printed — so the verdict read "the request never fired" and sent them hunting
303
+ * a UI wiring bug that did not exist, when the defect was the value the server answered with.
304
+ */
305
+ let bodyMismatch;
306
+ /**
307
+ * The prefix of a TRUNCATED body the needle was not found in. Held apart from `bodyMismatch`
308
+ * because the two are different verdicts: a full body without the needle decides the assertion,
309
+ * a truncated one cannot (#614).
310
+ */
311
+ let truncatedBody;
312
+ const requestState = newRequestBodyState();
313
+ const matches = events.filter((e) => {
314
+ if (e.type !== EventType.NET_REQUEST || e.t < since)
315
+ return false;
316
+ const d = e.data;
317
+ if (p.method !== undefined && str(d['method'])?.toUpperCase() !== p.method.toUpperCase()) {
318
+ return false;
319
+ }
320
+ if (p.urlContains !== undefined && !urlForMatch(d).includes(p.urlContains)) {
321
+ return false;
322
+ }
323
+ if (p.status !== undefined) {
324
+ const status = num(d['status']);
325
+ if (status === undefined) {
326
+ // Document-initiated subresources (link/css/img/manifest via resource timing) carry no
327
+ // readable status on engines without responseStatus. A failed assertion here would read
328
+ // "your change is broken" and send the caller to fix working code — the exact false
329
+ // negative the oracle exists to prevent. Downgrade to unknown instead.
330
+ unobservableStatus = true;
331
+ return false;
332
+ }
333
+ if (status !== p.status)
334
+ return false;
335
+ }
336
+ if (p.ok !== undefined && callSucceeded(d) !== p.ok)
337
+ return false;
338
+ if (p.bodyContains !== undefined) {
339
+ // The RESPONSE body only, and this is the whole point of the field. Searching the request too
340
+ // would let `bodyContains: "1187.01"` pass on the very defect it exists to catch: the app SENT
341
+ // that number, so it is in the request whatever the server then did with it. The server's answer
342
+ // is the one channel a UI cannot fake.
343
+ const response = str(d['responseBody']);
344
+ if (response === undefined) {
345
+ matchedButUnrecorded = true;
346
+ return false;
347
+ }
348
+ if (!response.includes(p.bodyContains)) {
349
+ // A needle missing from a body we only hold the FIRST N BYTES of is undecidable, not
350
+ // absent: the rest of the response was never recorded, so nothing here can say whether it
351
+ // was in there (#614). Grading it `pass: false` with "the response value is what differed"
352
+ // is the inversion the honesty rules exist to prevent — an unknown reported as decided,
353
+ // against a response that was very likely correct.
354
+ if (true === d['responseBodyTruncated']) {
355
+ truncatedBody ??= response;
356
+ return false;
357
+ }
358
+ bodyMismatch ??= response;
359
+ return false;
360
+ }
361
+ }
362
+ if (!checkRequestBody(d, p, requestState))
363
+ return false;
364
+ return true;
365
+ });
366
+ if (unobservableStatus && 0 === matches.length) {
367
+ // The url/method matched a document-initiated subresource whose engine could not read a status.
368
+ // "No matching call" would be a lie in both directions: it may have succeeded, it may have 404'd
369
+ // on exactly the path mistake the caller is hunting. Say the truth — not observable here.
370
+ return {
371
+ pass: false,
372
+ inconclusive: `a document-initiated request matching ${describeNetFilter(p)} was observed, but this engine does not expose its status code (resource timing without responseStatus) — assert on the element or route instead, or check the network tab`,
373
+ observed: 'a matching request with no readable status',
374
+ expected: `a status of ${String(p.status)} on ${JSON.stringify(p.urlContains ?? '*')}`,
375
+ assertion: 'net.unobservable-status',
376
+ };
377
+ }
378
+ if (matchedButUnrecorded && 0 === matches.length) {
379
+ return {
380
+ pass: false,
381
+ failureReason: `a call matched but its body was not recorded, so \`bodyContains\` could not be checked — enable it where the app calls connect(): reticle({ captureNetworkBodies: true })`,
382
+ observed: 'a matching call with no recorded body',
383
+ expected: `a body containing ${JSON.stringify(p.bodyContains)}`,
384
+ assertion: 'net.bodyContains',
385
+ };
386
+ }
387
+ const requestVerdict = requestBodyVerdict(requestState, p, matches.length);
388
+ if (requestVerdict !== undefined)
389
+ return requestVerdict;
390
+ // Ranked ABOVE the mismatch branch: when both a truncated and a full body missed the needle,
391
+ // the honest verdict is the undecidable one. Deciding on the full body would report a failure
392
+ // the truncated call may well contradict.
393
+ if (truncatedBody !== undefined && 0 === matches.length) {
394
+ return {
395
+ pass: false,
396
+ inconclusive: `a call matching ${describeNetFilter(p)} was answered with a body that was TRUNCATED before it was recorded, and ${JSON.stringify(p.bodyContains)} is not in the part that was kept — so this is undecidable, not a failure. Raise the capture cap or assert on something inside the recorded prefix`,
397
+ observed: `the first ${String(truncatedBody.length)} characters of a truncated response body ${JSON.stringify(clipBody(truncatedBody))}`,
398
+ expected: `a response body containing ${JSON.stringify(p.bodyContains)}`,
399
+ assertion: 'net.bodyContains',
400
+ };
401
+ }
402
+ if (bodyMismatch !== undefined && 0 === matches.length) {
403
+ // The call is there and its body is there; only the VALUE differs. Counting it as zero matches
404
+ // points at the wiring, which is the one place the defect is not.
405
+ return {
406
+ pass: false,
407
+ failureReason: `a call matching ${describeNetFilter(p)} was made and answered ${JSON.stringify(clipBody(bodyMismatch))}, which does not contain ${JSON.stringify(p.bodyContains)} — the request fired, the response value is what differed`,
408
+ observed: `response body ${JSON.stringify(clipBody(bodyMismatch))}`,
409
+ expected: `a response body containing ${JSON.stringify(p.bodyContains)}`,
410
+ assertion: 'net.bodyContains',
411
+ };
412
+ }
413
+ // `count` (exact) turns presence into a cardinality assertion — catches the double-submit /
414
+ // useEffect-double-fire / retry-storm regression class, where the request DID fire (presence passes)
415
+ // but fired the WRONG number of times. Without `count`, the matcher is presence-only (≥1).
416
+ if (p.count !== undefined) {
417
+ if (0 === matches.length) {
418
+ const download = nativeDownloadMiss(events, p);
419
+ if (download !== undefined)
420
+ return download;
421
+ }
422
+ if (matches.length !== p.count &&
423
+ 0 === matches.length &&
424
+ targetsUnobservedChannel(p) &&
425
+ !sawSubresources) {
426
+ return {
427
+ pass: false,
428
+ failureReason: unobservedChannelReason(p),
429
+ inconclusive: unobservedChannelReason(p),
430
+ assertion: 'net.count',
431
+ };
432
+ }
433
+ const counted = evalExactCount({
434
+ matched: matches.length,
435
+ want: p.count,
436
+ noun: 'network call(s)',
437
+ filter: describeNetFilter(p),
438
+ assertion: 'net.count',
439
+ });
440
+ // Same blind head, second door: "saw 0" over a whole-session window is the same claim the
441
+ // presence branch makes, and just as unable to see a startup call. A `count: 0` assertion is
442
+ // left alone on purpose — it PASSES here, and turning that green into a non-pass is a grade
443
+ // change, not a wording one.
444
+ return 0 === matches.length && 0 === since && counted.failureReason !== undefined
445
+ ? { ...counted, failureReason: `${counted.failureReason}${PRE_ATTACH_CAVEAT}` }
446
+ : counted;
447
+ }
448
+ const hit = matches[0];
449
+ if (hit === undefined) {
450
+ const download = nativeDownloadMiss(events, p);
451
+ if (download !== undefined)
452
+ return download;
453
+ }
454
+ if (hit === undefined && targetsUnobservedChannel(p) && !sawSubresources) {
455
+ const reason = unobservedChannelReason(p);
456
+ return {
457
+ pass: false,
458
+ failureReason: reason,
459
+ inconclusive: reason,
460
+ observed: observedNetCalls(events, p.urlContains),
461
+ expected: `at least one call matching ${describeNetFilter(p)}`,
462
+ assertion: 'net.unobserved-channel',
463
+ };
464
+ }
465
+ return hit !== undefined
466
+ ? { pass: true, evidence: netEvidence(hit.data, p) }
467
+ : {
468
+ pass: false,
469
+ failureReason: `no network call matched ${JSON.stringify(p)}${0 === since ? PRE_ATTACH_CAVEAT : ''}`,
470
+ // Same reasoning as the signal miss: "no matching call" cannot be told apart from "the app
471
+ // made no calls at all", and those need different fixes.
472
+ observed: observedNetCalls(events, p.urlContains),
473
+ expected: `at least one call matching ${JSON.stringify(p)}`,
474
+ assertion: 'net.present',
475
+ };
476
+ }
477
+ export function evalAnimation(events, p) {
478
+ const wantType = true === p.completed ? EventType.ANIM_END : EventType.ANIM_START;
479
+ const hit = events.find((e) => {
480
+ if (e.type !== wantType)
481
+ return false;
482
+ if (p.name !== undefined && str(e.data['name']) !== p.name)
483
+ return false;
484
+ if (p.target !== undefined && e.ref !== p.target)
485
+ return false;
486
+ return true;
487
+ });
488
+ return hit !== undefined
489
+ ? { pass: true, evidence: hit.data }
490
+ : {
491
+ pass: false,
492
+ failureReason: `no animation matched ${JSON.stringify(p)}`,
493
+ observed: 'no matching animation in the window',
494
+ expected: `an animation matching ${JSON.stringify(p)}`,
495
+ assertion: 'animation.present',
496
+ };
497
+ }
498
+ export function evalSignal(events, p) {
499
+ const isMatch = (e) => {
500
+ if (e.type !== EventType.SIGNAL)
501
+ return false;
502
+ if (p.name !== undefined && str(e.data['name']) !== p.name)
503
+ return false;
504
+ if (p.dataMatches !== undefined) {
505
+ const payload = (e.data['data'] ?? {});
506
+ if (!dataMatches(payload, p.dataMatches))
507
+ return false;
508
+ }
509
+ return true;
510
+ };
511
+ // `count` (exact) turns presence into a cardinality assertion, exactly as it does on `net`. The
512
+ // double-fire is invisible to every state-only oracle — a handler wired twice leaves the store in
513
+ // the right shape and fires the signal twice — and so is the wrong-name fire, where the intended
514
+ // signal fires once beside a mistyped sibling and a presence check cannot say which is which.
515
+ // Counting only what the MATCHER matched is what separates them. Omit = presence (≥1).
516
+ if (p.count !== undefined) {
517
+ return evalExactCount({
518
+ matched: events.filter(isMatch).length,
519
+ want: p.count,
520
+ noun: 'signal(s)',
521
+ filter: describeSignalFilter(p),
522
+ assertion: 'signal.count',
523
+ });
524
+ }
525
+ const hit = events.find(isMatch);
526
+ if (hit !== undefined)
527
+ return { pass: true, evidence: hit.data };
528
+ // Near-miss: show signals that fired with the same name (so the agent sees the real data).
529
+ const sameName = events
530
+ .filter((e) => e.type === EventType.SIGNAL && (p.name === undefined || str(e.data['name']) === p.name))
531
+ .map((e) => e.data['data'] ?? e.data);
532
+ return {
533
+ pass: false,
534
+ failureReason: sameName.length > 0
535
+ ? `signal '${p.name ?? '(any)'}' fired ${String(sameName.length)}x but data didn't match`
536
+ : `no signal matched ${JSON.stringify(p)}`,
537
+ observed: sameName.length > 0
538
+ ? `signal '${p.name ?? '(any)'}' fired ${String(sameName.length)}x, payload: ${JSON.stringify(sameName[0])}`
539
+ : // Name what DID fire: a typo'd signal name and a genuinely dead action produce the same
540
+ // sentence otherwise, and the agent cannot tell them apart. See observed-in-window.ts.
541
+ `signal '${p.name ?? '(any)'}' never fired; ${describeObserved('signals', events.filter((e) => e.type === EventType.SIGNAL).map((e) => str(e.data['name']) ?? ''))}`,
542
+ expected: p.dataMatches === undefined
543
+ ? `signal '${p.name ?? '(any)'}' to fire`
544
+ : `signal '${p.name ?? '(any)'}' with payload matching ${JSON.stringify(p.dataMatches)}`,
545
+ // Two distinct failures behind one prose line: never fired at all, versus fired with the wrong
546
+ // payload. They call for different fixes, so the agent should not have to tell them apart by
547
+ // reading the sentence.
548
+ assertion: sameName.length > 0 ? 'signal.payload' : 'signal.absent',
549
+ evidence: sameName.length > 0 ? { nearMiss: sameName } : undefined,
550
+ };
551
+ }
552
+ /**
553
+ * Assert a value inside a registered store — the deterministic source of truth no DOM/network read
554
+ * can reach. Reads the store (STATE_READ), walks `path` (dot-path, numeric array indices), and matches
555
+ * the value against `equals` (a literal, `*` for presence, or a `{$gte,$contains,$length,…}` operator
556
+ * pattern — same matcher as signal `dataMatches`). This is what turns "the UI lies about the store"
557
+ * from a manual three-step catch into a one-line, LLM-free regression invariant a flow can carry.
558
+ */
559
+ /**
560
+ * Activity that resets the "quiet" timer for a `settled` predicate: network calls and STRUCTURAL DOM
561
+ * mutations (nodes added/removed, attributes changed). Deliberately EXCLUDES `dom.text` and animation
562
+ * frames: a count-up counter, a spinner, a pulsing dot, or any looping CSS animation emits a text/anim
563
+ * event every frame forever, so an app with ambient motion would NEVER go quiet (observed live: one
564
+ * login flooded 319 dom.text events from the dashboard's count-up animations). That is the same trap
565
+ * that got Playwright's `networkidle` deprecated. Network + structural DOM are the real "the app is
566
+ * still doing work" signals; for an outcome gated on an animation finishing, assert that specific
567
+ * consequence (signal/net) instead of relying on settle.
568
+ */
569
+ const SETTLE_ACTIVITY = new Set([
570
+ EventType.NET_REQUEST,
571
+ EventType.DOM_ADDED,
572
+ EventType.DOM_REMOVED,
573
+ EventType.DOM_ATTR,
574
+ ]);
575
+ /** The three net-shaped event types a URL can be read off — the only ones dev tooling can produce. */
576
+ const NET_TYPES = new Set([
577
+ EventType.NET_PENDING,
578
+ EventType.NET_REQUEST,
579
+ EventType.NET_STREAM,
580
+ ]);
581
+ /** Default quiet window — enough to absorb a render+xhr settle without waiting on slow polls. */
582
+ const DEFAULT_QUIET_MS = 500;
583
+ /**
584
+ * "The page has gone quiet": no network/DOM/animation activity for at least `quietMs`. Needs the
585
+ * wall-clock `now` (in the buffer's time base) because "no activity in the last N ms" is relative to
586
+ * now, not to any buffered event — so `now` is injected (CLAUDE.md rule 7), and the wait loop's
587
+ * poll interval is what eventually flips this to pass once activity stops.
588
+ */
589
+ export function evalSettled(allEvents, p, now) {
590
+ const quietMs = p.quietMs ?? DEFAULT_QUIET_MS;
591
+ // Dev-tooling traffic is the framework talking about ITSELF (see DevToolingChannel) and says
592
+ // nothing about whether the app finished its work — but it was holding settle open. Dropped from
593
+ // both halves of the calculation below (in-flight AND the quiet timer) and DISCLOSED on the
594
+ // evidence, never silently swallowed.
595
+ const ignoredDevTooling = [];
596
+ const events = allEvents.filter((e) => {
597
+ if (!NET_TYPES.has(e.type))
598
+ return true;
599
+ const url = str(e.data['url']);
600
+ if (!isDevToolingUrl(url))
601
+ return true;
602
+ if (url !== undefined && !ignoredDevTooling.includes(url))
603
+ ignoredDevTooling.push(url);
604
+ return false;
605
+ });
606
+ const disclosure = 0 === ignoredDevTooling.length ? {} : { ignoredDevTooling };
607
+ // A request that STARTED (NET_PENDING) but never completed (NET_REQUEST with the same id) is
608
+ // still in flight — the page is NOT settled no matter how quiet the DOM has gone. Without this,
609
+ // a slow save reads as "settled" the instant its spinner stops mutating the DOM: the exact
610
+ // false-green `settled` exists to prevent.
611
+ //
612
+ // COUNT per id, don't just set-membership: a retry that reuses a request id (two NET_PENDING, one
613
+ // NET_REQUEST) would mark the id "done" and hide the second, still-flying request — an in-flight
614
+ // UNDERCOUNT that greens settle while a request is live. In-flight for an id is pendings minus
615
+ // completions (floored at 0); unkeyed pendings each count as one.
616
+ const pendingById = new Map();
617
+ const doneById = new Map();
618
+ let unkeyedPending = 0;
619
+ for (const e of events) {
620
+ if (e.type === EventType.NET_PENDING) {
621
+ const id = str(e.data['id']);
622
+ if (id === undefined)
623
+ unkeyedPending += 1;
624
+ else
625
+ pendingById.set(id, (pendingById.get(id) ?? 0) + 1);
626
+ }
627
+ else if (e.type === EventType.NET_REQUEST) {
628
+ const id = str(e.data['id']);
629
+ if (id !== undefined)
630
+ doneById.set(id, (doneById.get(id) ?? 0) + 1);
631
+ }
632
+ }
633
+ let inFlight = unkeyedPending;
634
+ for (const [id, pending] of pendingById) {
635
+ inFlight += Math.max(0, pending - (doneById.get(id) ?? 0));
636
+ }
637
+ // A completed request whose BODY is still streaming is not a finished request. `fetch` resolves at
638
+ // HEADERS, so on a Next.js App Router page the RSC payload reported complete 16 ms in while the
639
+ // Suspense boundary's content arrived 889 ms later — and the silence between them read as a settled
640
+ // page with a loading spinner still on screen. An OPEN with no CLOSE is in flight, counted the same
641
+ // way as a pending with no completion.
642
+ const openStreams = new Set();
643
+ for (const e of events) {
644
+ if (e.type !== EventType.NET_STREAM)
645
+ continue;
646
+ const id = str(e.data['id']);
647
+ if (id === undefined)
648
+ continue;
649
+ const direction = str(e.data['direction']);
650
+ if (StreamDirection.OPEN === direction)
651
+ openStreams.add(id);
652
+ else if (StreamDirection.CLOSE === direction)
653
+ openStreams.delete(id);
654
+ }
655
+ const streaming = openStreams.size;
656
+ if (inFlight + streaming > 0) {
657
+ const what = 0 === streaming
658
+ ? `${String(inFlight)} request(s) still in flight`
659
+ : 0 === inFlight
660
+ ? `${String(streaming)} response body(ies) still streaming`
661
+ : `${String(inFlight)} request(s) in flight and ${String(streaming)} response body(ies) still streaming`;
662
+ return {
663
+ pass: false,
664
+ failureReason: `not settled: ${what}`,
665
+ observed: what,
666
+ expected: 'no requests in flight and no response bodies still streaming',
667
+ assertion: 'settled.in-flight',
668
+ evidence: {
669
+ settled: false,
670
+ inFlight,
671
+ ...(streaming > 0 ? { streaming } : {}),
672
+ ...disclosure,
673
+ },
674
+ };
675
+ }
676
+ let lastT = -1;
677
+ let lastType;
678
+ for (const e of events) {
679
+ if (SETTLE_ACTIVITY.has(e.type) && e.t > lastT) {
680
+ lastT = e.t;
681
+ lastType = e.type;
682
+ }
683
+ }
684
+ if (lastT < 0) {
685
+ return {
686
+ pass: true,
687
+ evidence: { settled: true, quietForMs: null, note: 'no activity to settle', ...disclosure },
688
+ };
689
+ }
690
+ const quietForMs = now - lastT;
691
+ if (quietForMs >= quietMs) {
692
+ return {
693
+ pass: true,
694
+ evidence: { settled: true, quietForMs, lastActivity: lastType, ...disclosure },
695
+ };
696
+ }
697
+ return {
698
+ pass: false,
699
+ failureReason: `not settled: last activity (${String(lastType)}) ${String(quietForMs)}ms ago, need ${String(quietMs)}ms quiet`,
700
+ observed: `last activity was ${String(lastType)}, ${String(quietForMs)}ms ago`,
701
+ expected: `${String(quietMs)}ms of quiet`,
702
+ assertion: 'settled.quiet',
703
+ evidence: { quietForMs, lastActivity: lastType, ...disclosure },
704
+ // The one failure in this file that knows exactly when it could stop being one: if nothing else
705
+ // happens, the window closes in this many ms. A waiter that re-checks THEN instead of on its next
706
+ // blind tick stops paying up to a full poll interval on the hottest call in the product. Only a
707
+ // hint — the predicate is still evaluated at that moment, and can still fail.
708
+ retryAfterMs: quietMs - quietForMs,
709
+ };
710
+ }