@reticlehq/engine 3.5.0 → 3.7.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 (57) hide show
  1. package/dist/disagreement/body-failures.js +2 -1
  2. package/dist/disagreement/contradiction-evidence.d.ts +73 -1
  3. package/dist/disagreement/contradiction-evidence.js +154 -6
  4. package/dist/disagreement/contradiction-types.d.ts +8 -1
  5. package/dist/disagreement/contradictions.d.ts +17 -1
  6. package/dist/disagreement/contradictions.js +111 -38
  7. package/dist/disagreement/echo-mismatch.js +42 -3
  8. package/dist/disagreement/reconcile.js +15 -0
  9. package/dist/disagreement/stale-response.js +37 -2
  10. package/dist/evidence/accepted-write.d.ts +26 -2
  11. package/dist/evidence/accepted-write.js +35 -18
  12. package/dist/evidence/already-true.d.ts +16 -0
  13. package/dist/evidence/already-true.js +48 -0
  14. package/dist/evidence/baseline.js +2 -6
  15. package/dist/evidence/blind-spots.d.ts +14 -3
  16. package/dist/evidence/blind-spots.js +48 -10
  17. package/dist/evidence/body-capture-remedy.d.ts +10 -0
  18. package/dist/evidence/body-capture-remedy.js +15 -2
  19. package/dist/evidence/instrumentation-gaps.js +3 -1
  20. package/dist/evidence/state-bookkeeping.d.ts +2 -0
  21. package/dist/evidence/state-bookkeeping.js +2 -0
  22. package/dist/evidence/superseded-checks.d.ts +29 -0
  23. package/dist/evidence/superseded-checks.js +30 -0
  24. package/dist/evidence/unsettled.js +4 -2
  25. package/dist/evidence/verified.d.ts +8 -1
  26. package/dist/evidence/verified.js +42 -4
  27. package/dist/question/declared.d.ts +24 -4
  28. package/dist/question/declared.js +26 -5
  29. package/dist/question/predicate/name-near-miss.d.ts +24 -0
  30. package/dist/question/predicate/name-near-miss.js +39 -0
  31. package/dist/question/predicate/net-blind-spots.d.ts +49 -0
  32. package/dist/question/predicate/net-blind-spots.js +153 -0
  33. package/dist/question/predicate/predicate-compare.js +13 -4
  34. package/dist/question/predicate/predicate-element.d.ts +15 -1
  35. package/dist/question/predicate/predicate-element.js +108 -7
  36. package/dist/question/predicate/predicate-eval-kit.d.ts +25 -0
  37. package/dist/question/predicate/predicate-eval-kit.js +31 -0
  38. package/dist/question/predicate/predicate-eval.d.ts +17 -2
  39. package/dist/question/predicate/predicate-eval.js +117 -180
  40. package/dist/question/predicate/predicate-parse.js +153 -13
  41. package/dist/question/predicate/predicate-request-body.d.ts +6 -1
  42. package/dist/question/predicate/predicate-request-body.js +7 -2
  43. package/dist/question/predicate/predicate-route.d.ts +2 -0
  44. package/dist/question/predicate/predicate-route.js +30 -0
  45. package/dist/question/predicate/predicate-schema.d.ts +11 -0
  46. package/dist/question/predicate/predicate-schema.js +110 -24
  47. package/dist/question/predicate/predicate-session.d.ts +10 -0
  48. package/dist/question/predicate/predicate-state.js +7 -0
  49. package/dist/question/predicate/predicate-to-links.js +1 -0
  50. package/dist/question/predicate/predicate.js +76 -25
  51. package/dist/question/predicate/split-text-miss.d.ts +6 -0
  52. package/dist/question/predicate/split-text-miss.js +10 -0
  53. package/dist/question/reaction.d.ts +1 -1
  54. package/dist/question/reaction.js +1 -1
  55. package/dist/state-bookkeeping.d.ts +25 -0
  56. package/dist/state-bookkeeping.js +70 -0
  57. package/package.json +2 -2
@@ -1,11 +1,24 @@
1
- import { EventType, PredicateKind, StreamDirection, isDevToolingUrl, urlForMatch, REDACTED_VALUE, } from '@reticlehq/core';
1
+ import { EventType, NetInitiator, PredicateKind, StreamDirection, isDevToolingUrl, isForeignTraffic, urlForMatch, REDACTED_VALUE, } from '@reticlehq/core';
2
2
  import { describeObserved } from './observed-in-window.js';
3
3
  import { netEvidence } from './net-evidence.js';
4
4
  import { checkRequestBody, newRequestBodyState, requestBodyVerdict, } from './predicate-request-body.js';
5
5
  export { evalConsole } from './predicate-console.js';
6
6
  import { clipBody, dataMatches, describeBodyFieldMiss, describeFieldMiss, describeNetFilter, matchJsonBody, num, redactedOnPath, str, } from './predicate-eval-kit.js';
7
7
  import { keyFragmentOnly } from './body-key-fragment.js';
8
+ import { PRE_ATTACH_CAVEAT, nativeDownloadReason, targetsNativeDownload, targetsUnobservedChannel, unobservedChannelReason, } from './net-blind-spots.js';
8
9
  export { clipBody, dataMatches, describeNetFilter, matchValue, str, } from './predicate-eval-kit.js';
10
+ /** The oracle a net body clause reports, so an agent can branch on which one decided. */
11
+ const NetBodyAssertion = {
12
+ CONTAINS: 'net.bodyContains',
13
+ MATCHES: 'net.bodyMatches',
14
+ };
15
+ /** A truncated body missed a `bodyContains`: the kept prefix can still answer a substring. */
16
+ const TRUNCATED_PREFIX_REMEDY = "Raise it past this response's size and re-run, or assert on something inside the recorded prefix";
17
+ /**
18
+ * A truncated body missed a `bodyMatches`. That clause parses the whole body and a JSON prefix never
19
+ * parses, so "assert inside the prefix" changes nothing for it (#1417): name what can work instead.
20
+ */
21
+ const TRUNCATED_MATCHES_REMEDY = "Raise it past this response's size and re-run. `bodyMatches` parses the whole body, and a JSON prefix never parses, so it cannot be judged on the kept part: to assert on what was kept, use `bodyContains` with a substring from it";
9
22
  // The predicate SHAPE — the discriminated union, its aliases and its zod schema — lives in
10
23
  // predicate-schema.ts, and is re-exported here: the two halves are ONE public surface.
11
24
  export * from './predicate-schema.js';
@@ -86,116 +99,10 @@ function evalExactCount(args) {
86
99
  assertion,
87
100
  };
88
101
  }
89
- /**
90
- * URL suffixes only the DOCUMENT fetches, which the network observer therefore never records.
91
- *
92
- * `network.ts` patches `fetch` and `XMLHttpRequest` and nothing else, so `<link rel=icon>`,
93
- * `<link rel=manifest>`, stylesheets, fonts and `<img src>` are invisible to it. "No matching call"
94
- * and "that class of call is not observed" are then indistinguishable, and the miss graded
95
- * `assertion_failed` — a false RED. Reported from the field: an assert over `/favicon.ico`,
96
- * `/site.webmanifest` and `/apple-touch-icon.png` returned `verified:"no"` while curl showed all
97
- * three answering 200. A false negative here is worse than an unknown, because an agent that trusts
98
- * it goes and "fixes" working code.
99
- *
100
- * Deliberately NOT here: `.js` and `.json`. Both are routinely fetched via `fetch`/XHR — a module
101
- * preload and an API call can share a suffix — so downgrading them would hide real misses. This list
102
- * is only the suffixes for which the document is the sole plausible initiator.
103
- *
104
- * This began as the smaller half of #447: it did not make these requests observable, it stopped
105
- * Reticle claiming they did not happen. The other half, observing them via resource timing, has
106
- * since landed in the browser SDK, so the two halves are no longer independent and this downgrade is
107
- * now GATED: when the event stream carries at least one document-initiated record, the observer is
108
- * demonstrably live and a miss over these suffixes is real evidence, graded a plain failure. Only a
109
- * page whose stream holds no resource entry at all keeps the honest "cannot tell apart" answer,
110
- * because there the observer may simply not exist.
111
- */
112
- const DOCUMENT_ONLY_SUFFIXES = [
113
- '.ico',
114
- '.png',
115
- '.jpg',
116
- '.jpeg',
117
- '.gif',
118
- '.svg',
119
- '.webp',
120
- '.avif',
121
- '.bmp',
122
- '.css',
123
- '.woff',
124
- '.woff2',
125
- '.ttf',
126
- '.otf',
127
- '.eot',
128
- '.webmanifest',
129
- ];
130
- /**
131
- * File suffixes a click typically downloads or navigates to as a document, never as fetch/XHR.
132
- *
133
- * Sibling of DOCUMENT_ONLY_SUFFIXES, not a member of it. Those are subresources: once resource
134
- * timing is live, a miss is evidence. A click on `<a href="/export.pdf">` is a navigation (or a
135
- * Content-Disposition attachment). Resource timing of stylesheets does not make it visible, so
136
- * grading the miss as "0 network calls" / a 404 is the lie #805 exists to stop — even on a page
137
- * whose observer is running. `.js` / `.json` stay off this list for the same reason they stay off
138
- * the other: they are routinely fetched.
139
- */
140
- const NATIVE_DOWNLOAD_SUFFIXES = [
141
- '.pdf',
142
- '.csv',
143
- '.tsv',
144
- '.zip',
145
- '.gz',
146
- '.tar',
147
- '.xlsx',
148
- '.xls',
149
- '.docx',
150
- '.doc',
151
- '.pptx',
152
- '.ppt',
153
- '.ods',
154
- '.odt',
155
- '.rtf',
156
- '.7z',
157
- '.rar',
158
- ];
159
- /**
160
- * Does this filter target a class of request the observer cannot see?
161
- *
162
- * Read off `urlContains` only, and only when the pattern ENDS in one of the suffixes — a filter of
163
- * `/api/` that happens to contain `.css` somewhere in a query string is still an ordinary XHR
164
- * target. Query strings and fragments are stripped first, since `favicon.ico?v=2` is the same asset.
165
- */
166
- function filterPath(urlContains) {
167
- return (urlContains.split('#')[0] ?? '').split('?')[0]?.toLowerCase() ?? '';
168
- }
169
- /**
170
- * Does this filter target a class of request the observer cannot see?
171
- *
172
- * Read off `urlContains` only, and only when the pattern ENDS in one of the suffixes — a filter of
173
- * `/api/` that happens to contain `.css` somewhere in a query string is still an ordinary XHR
174
- * target. Query strings and fragments are stripped first, since `favicon.ico?v=2` is the same asset.
175
- */
176
- function targetsUnobservedChannel(p) {
177
- const url = p.urlContains;
178
- if (undefined === url)
179
- return false;
180
- return DOCUMENT_ONLY_SUFFIXES.some((suffix) => filterPath(url).endsWith(suffix));
181
- }
182
- function targetsNativeDownload(p) {
183
- const url = p.urlContains;
184
- if (undefined === url)
185
- return false;
186
- return NATIVE_DOWNLOAD_SUFFIXES.some((suffix) => filterPath(url).endsWith(suffix));
187
- }
188
- function nativeDownloadReason(p) {
189
- return (`no fetch or XHR matched ${describeNetFilter(p)}. A native download or document navigation ` +
190
- `(an <a href> to a file, a Content-Disposition attachment, <a download>) never goes through ` +
191
- `fetch or XMLHttpRequest, so an empty net window is not a 404 and is not evidence the export ` +
192
- `failed. This is unobservable on the net channel. Assert the link href, or check the file ` +
193
- `outside the browser — Reticle cannot see the bytes land`);
194
- }
195
102
  function nativeDownloadMiss(events, p) {
196
- if (!targetsNativeDownload(p))
103
+ if (!targetsNativeDownload(p.urlContains))
197
104
  return undefined;
198
- const reason = nativeDownloadReason(p);
105
+ const reason = nativeDownloadReason(describeNetFilter(p));
199
106
  return {
200
107
  pass: false,
201
108
  failureReason: reason,
@@ -245,44 +152,6 @@ export function isDocumentInitiated(event) {
245
152
  function observerSawSubresources(events) {
246
153
  return events.some(isDocumentInitiated);
247
154
  }
248
- /** The sentence both zero-match branches hand to `inconclusive`. */
249
- function unobservedChannelReason(p) {
250
- return (`no call matched ${describeNetFilter(p)}, and no document-initiated load was recorded either, ` +
251
- `so this page exposed no resource timing to read: Reticle observes fetch and XMLHttpRequest ` +
252
- `directly, while a request the document initiates (<link rel=icon|manifest|preload>, a ` +
253
- `stylesheet, a font, <img src>) leaves no record, and that state cannot be told apart from the ` +
254
- `request having been made. ` +
255
- `Nothing here says the app is wrong. Check it outside the browser, or assert something the ` +
256
- `document does not fetch on its own`);
257
- }
258
- /**
259
- * Appended to a zero-match `net` negative whose window starts at SDK attach.
260
- *
261
- * Every event's `t` is stamped `performance.now() - #start`, where `#start` is taken when the SDK
262
- * is constructed, so `t` is never negative and a window with `since === 0` begins AT attach — never
263
- * before it. Whatever the page did between navigation start and attach left no event at all, so
264
- * "no matching call" over such a window cannot be told apart from "the call was made while nothing
265
- * was watching yet".
266
- *
267
- * The gap is routine rather than exotic: a `fetch` from an effect in a root provider, or a classic
268
- * `<script>` at the end of `<body>`, fires before a deferred module script has run. Read as proof
269
- * the request was never made, that sends a reader looking for a defect in code that works —
270
- * restarting dev servers and re-reading providers to establish that the request was invisible rather
271
- * than absent.
272
- *
273
- * Same argument as DOCUMENT_ONLY_SUFFIXES one axis over: that one is a channel Reticle does not
274
- * watch, this is a stretch of TIME it was not yet watching.
275
- *
276
- * The grade is deliberately NOT downgraded to `inconclusive`. A missing API call is the finding this
277
- * oracle exists to make, and it is the strongest grade available for the startup class — session
278
- * restore, feature flags, bootstrap config — which is exactly the class that silently breaks on
279
- * reload. Every window an action opens carries `since > 0` and is untouched. What changes is only
280
- * what the negative CLAIMS: it stops asserting the request never happened, and names the assertion
281
- * that can settle it, because the state such a request produces IS observable after attach.
282
- */
283
- const PRE_ATTACH_CAVEAT = ' — note that this window starts where the SDK attached, and requests made before that are never ' +
284
- 'captured, so a miss here cannot tell a call that was never made apart from one made before the ' +
285
- 'page connected; if the call is expected during startup, assert on the state it produces instead';
286
155
  /**
287
156
  * The response-body clause as the caller wrote it, for a verdict that has to quote it.
288
157
  *
@@ -326,6 +195,8 @@ export function evalNet(events, p) {
326
195
  * a truncated one cannot (#614).
327
196
  */
328
197
  let truncatedBody;
198
+ // Which clause the truncated body missed: a predicate can carry both, and the remedy for each differs.
199
+ let truncatedClause;
329
200
  /**
330
201
  * A `bodyContains` needle that was FOUND, and found only inside a key name (#987).
331
202
  *
@@ -361,6 +232,8 @@ export function evalNet(events, p) {
361
232
  }
362
233
  if (p.ok !== undefined && callSucceeded(d) !== p.ok)
363
234
  return false;
235
+ if (!checkRequestBody(d, p, requestState))
236
+ return false;
364
237
  if (p.bodyContains !== undefined || p.bodyMatches !== undefined) {
365
238
  // The RESPONSE body only, and this is the whole point of these fields. Searching the request
366
239
  // too would let `bodyContains: "1187.01"` pass on the very defect it exists to catch: the app
@@ -376,16 +249,18 @@ export function evalNet(events, p) {
376
249
  // there (#614). Grading it `pass: false` with "the response value is what differed" is the
377
250
  // inversion the honesty rules exist to prevent — an unknown reported as decided, against a
378
251
  // response that was very likely correct.
379
- const missed = () => {
380
- if (true === d['responseBodyTruncated'])
252
+ const missed = (clause) => {
253
+ if (true === d['responseBodyTruncated']) {
381
254
  truncatedBody ??= response;
255
+ truncatedClause ??= clause;
256
+ }
382
257
  else
383
258
  bodyMismatch ??= response;
384
259
  return false;
385
260
  };
386
261
  if (p.bodyContains !== undefined) {
387
262
  if (!response.includes(p.bodyContains))
388
- return missed();
263
+ return missed(NetBodyAssertion.CONTAINS);
389
264
  const fragment = keyFragmentOnly(response, p.bodyContains);
390
265
  if (fragment !== undefined) {
391
266
  keyFragment ??= { key: fragment, body: response };
@@ -395,15 +270,13 @@ export function evalNet(events, p) {
395
270
  if (p.bodyMatches !== undefined) {
396
271
  const verdict = matchJsonBody(response, p.bodyMatches);
397
272
  if ('mismatch' === verdict)
398
- return missed();
273
+ return missed(NetBodyAssertion.MATCHES);
399
274
  if ('match' !== verdict) {
400
275
  redactedResponseField ??= verdict.redacted;
401
276
  return false;
402
277
  }
403
278
  }
404
279
  }
405
- if (!checkRequestBody(d, p, requestState))
406
- return false;
407
280
  return true;
408
281
  });
409
282
  if (unobservableStatus && 0 === matches.length) {
@@ -424,7 +297,7 @@ export function evalNet(events, p) {
424
297
  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 })`,
425
298
  observed: 'a matching call with no recorded body',
426
299
  expected: `a body carrying ${wantedBody(p)}`,
427
- assertion: 'net.bodyContains',
300
+ assertion: NetBodyAssertion.CONTAINS,
428
301
  };
429
302
  }
430
303
  if (keyFragment !== undefined && 0 === matches.length) {
@@ -434,7 +307,7 @@ export function evalNet(events, p) {
434
307
  inconclusive: `a call matching ${describeNetFilter(p)} was answered with a body where ${JSON.stringify(p.bodyContains)} appears ONLY inside the key name ${JSON.stringify(keyFragment.key)} — no value in the response contains it, so this substring proves nothing about what any field holds. Assert the field itself: \`bodyMatches: { "<field>": <value> }\``,
435
308
  observed: `response body ${JSON.stringify(clipBody(keyFragment.body))}`,
436
309
  expected: `a response body carrying ${JSON.stringify(p.bodyContains)} as a value, or as a whole key`,
437
- assertion: 'net.bodyContains',
310
+ assertion: NetBodyAssertion.CONTAINS,
438
311
  };
439
312
  }
440
313
  if (redactedResponseField !== undefined && 0 === matches.length) {
@@ -444,24 +317,31 @@ export function evalNet(events, p) {
444
317
  inconclusive: `a call matching ${describeNetFilter(p)} was answered, but its ${field} was REDACTED before the body was recorded, so this clause cannot be judged — a redacted field is unknown, not different. Assert on a non-sensitive key, or on the effect the value had`,
445
318
  observed: `a matching response whose ${field} is ${REDACTED_VALUE}`,
446
319
  expected: `a response body matching ${JSON.stringify(p.bodyMatches)}`,
447
- assertion: 'net.bodyMatches',
320
+ assertion: NetBodyAssertion.MATCHES,
448
321
  };
449
322
  }
450
- const requestVerdict = requestBodyVerdict(requestState, p, matches.length);
451
- if (requestVerdict !== undefined)
452
- return requestVerdict;
453
323
  // Ranked ABOVE the mismatch branch: when both a truncated and a full body missed the needle,
454
324
  // the honest verdict is the undecidable one. Deciding on the full body would report a failure
455
325
  // the truncated call may well contradict.
456
326
  if (truncatedBody !== undefined && 0 === matches.length) {
327
+ // `bodyMatches` parses the whole body, and a JSON prefix never parses, so "assert on something
328
+ // inside the recorded prefix" changes nothing for it: the same clause on the same prefix is the
329
+ // same unknown. Name what can work for the clause that was actually asked (#1417). The grade
330
+ // stays inconclusive either way: a partial parse must not decide it, since a later duplicate key
331
+ // could overturn whatever the prefix seemed to say.
332
+ const missedMatch = NetBodyAssertion.MATCHES === truncatedClause;
333
+ const remedy = missedMatch ? TRUNCATED_MATCHES_REMEDY : TRUNCATED_PREFIX_REMEDY;
457
334
  return {
458
335
  pass: false,
459
- inconclusive: `a call matching ${describeNetFilter(p)} was answered with a body that was TRUNCATED before it was recorded, and ${wantedBody(p)} is not in the part that was kept — so this is undecidable, not a failure. The cap is per-body and set where the app calls connect(): \`reticle.connect({ captureNetworkBodies: true, networkBodyMaxChars: 65536 })\`, or for the Vite plugin \`reticle({ networkBodyMaxChars: 65536 })\` / VITE_RETICLE_BODY_MAX_CHARS=65536 (default 8192, max 262144). An SDK older than this daemon ignores the option; a version skew on the session says so. Raise it past this response's size and re-run, or assert on something inside the recorded prefix`,
336
+ inconclusive: `a call matching ${describeNetFilter(p)} was answered with a body that was TRUNCATED before it was recorded, and ${wantedBody(p)} is not in the part that was kept — so this is undecidable, not a failure. The cap is per-body and set where the app calls connect(): \`reticle.connect({ captureNetworkBodies: true, networkBodyMaxChars: 65536 })\`, or for the Vite plugin \`reticle({ networkBodyMaxChars: 65536 })\` / VITE_RETICLE_BODY_MAX_CHARS=65536 (default 8192, max 262144). An SDK older than this daemon ignores the option; a version skew on the session says so. ${remedy}`,
460
337
  observed: `the first ${String(truncatedBody.length)} characters of a truncated response body ${JSON.stringify(clipBody(truncatedBody))}`,
461
338
  expected: `a response body carrying ${wantedBody(p)}`,
462
- assertion: 'net.bodyContains',
339
+ assertion: truncatedClause ?? NetBodyAssertion.CONTAINS,
463
340
  };
464
341
  }
342
+ const requestVerdict = requestBodyVerdict(requestState, p, matches.length, bodyMismatch);
343
+ if (requestVerdict !== undefined)
344
+ return requestVerdict;
465
345
  if (bodyMismatch !== undefined && 0 === matches.length) {
466
346
  // The call is there and its body is there; only the VALUE differs. Counting it as zero matches
467
347
  // points at the wiring, which is the one place the defect is not. A field clause also names the
@@ -473,7 +353,7 @@ export function evalNet(events, p) {
473
353
  failureReason: `a call matching ${describeNetFilter(p)} was made and answered ${JSON.stringify(clipBody(bodyMismatch))}, which does not carry ${wantedBody(p)}${because} — the request fired, the response value is what differed`,
474
354
  observed: `response body ${JSON.stringify(clipBody(bodyMismatch))}${because}`,
475
355
  expected: `a response body carrying ${wantedBody(p)}`,
476
- assertion: 'net.bodyContains',
356
+ assertion: NetBodyAssertion.CONTAINS,
477
357
  };
478
358
  }
479
359
  // `count` (exact) turns presence into a cardinality assertion — catches the double-submit /
@@ -487,12 +367,12 @@ export function evalNet(events, p) {
487
367
  }
488
368
  if (matches.length !== p.count &&
489
369
  0 === matches.length &&
490
- targetsUnobservedChannel(p) &&
370
+ targetsUnobservedChannel(p.urlContains) &&
491
371
  !sawSubresources) {
492
372
  return {
493
373
  pass: false,
494
- failureReason: unobservedChannelReason(p),
495
- inconclusive: unobservedChannelReason(p),
374
+ failureReason: unobservedChannelReason(describeNetFilter(p)),
375
+ inconclusive: unobservedChannelReason(describeNetFilter(p)),
496
376
  assertion: 'net.count',
497
377
  };
498
378
  }
@@ -517,8 +397,8 @@ export function evalNet(events, p) {
517
397
  if (download !== undefined)
518
398
  return download;
519
399
  }
520
- if (hit === undefined && targetsUnobservedChannel(p) && !sawSubresources) {
521
- const reason = unobservedChannelReason(p);
400
+ if (hit === undefined && targetsUnobservedChannel(p.urlContains) && !sawSubresources) {
401
+ const reason = unobservedChannelReason(describeNetFilter(p));
522
402
  return {
523
403
  pass: false,
524
404
  failureReason: reason,
@@ -684,30 +564,87 @@ const NET_TYPES = new Set([
684
564
  ]);
685
565
  /** Default quiet window — enough to absorb a render+xhr settle without waiting on slow polls. */
686
566
  const DEFAULT_QUIET_MS = 500;
567
+ /**
568
+ * Did the browser LEAVE for this record, rather than make a request whose result we will see?
569
+ *
570
+ * `NetInitiator.NAVIGATION` is emitted as a `NET_PENDING` — because that is exactly what it is — but
571
+ * its completion goes to a document this session does not live into, so no `NET_REQUEST` can ever
572
+ * match it. Counting it as outstanding means the first click on any outbound link or download button
573
+ * wedges settle on that page for the rest of the session.
574
+ *
575
+ * The act wait (`server/src/surface/tools/act/settle-in-flight.ts`) has always excluded it and
576
+ * `core/src/wire/net.ts` says it must be; this predicate counted it, so `act_and_wait { until:
577
+ * settled }` after a plain `<a href>` never passed and agents dropped `settled` from their `until`.
578
+ * Spelled against the shared constant rather than the string, so the two settle decisions cannot
579
+ * drift onto two vocabularies.
580
+ */
581
+ const isDeparture = (data) => data['initiator'] === NetInitiator.NAVIGATION;
687
582
  /**
688
583
  * "The page has gone quiet": no network/DOM/animation activity for at least `quietMs`. Needs the
689
584
  * wall-clock `now` (in the buffer's time base) because "no activity in the last N ms" is relative to
690
- * now, not to any buffered event — so `now` is injected (CLAUDE.md rule 7), and the wait loop's
585
+ * now, not to any buffered event — so `now` is injected (AGENTS.md rule 7), and the wait loop's
691
586
  * poll interval is what eventually flips this to pass once activity stops.
692
587
  */
693
- export function evalSettled(allEvents, p, now) {
588
+ export function evalSettled(allEvents, p, now, scope) {
694
589
  const quietMs = p.quietMs ?? DEFAULT_QUIET_MS;
695
- // Dev-tooling traffic is the framework talking about ITSELF (see DevToolingChannel) and says
696
- // nothing about whether the app finished its work — but it was holding settle open. Dropped from
697
- // both halves of the calculation below (in-flight AND the quiet timer) and DISCLOSED on the
698
- // evidence, never silently swallowed.
590
+ // Three kinds of traffic say nothing about whether the APP finished its work, and all three are
591
+ // dropped from BOTH halves of the calculation below (in-flight AND the quiet timer) and DISCLOSED
592
+ // on the evidence, never silently swallowed:
593
+ //
594
+ // - dev tooling, the framework talking about ITSELF (see DevToolingChannel);
595
+ // - a departure, which by construction can never complete (see `NetInitiator.NAVIGATION`);
596
+ // - somebody else's host, or a same-origin endpoint the project declared (`isForeignTraffic`).
597
+ //
598
+ // The last two were counted here while `settle-in-flight.ts` and the contradiction pass dropped
599
+ // them, so the product held two answers to one question. The predicate's answer was the wrong one:
600
+ // after a plain `<a href>` click it reported "1 request(s) still in flight" forever, and a vendor
601
+ // beacon made every assertion on such an app return `unknown / outcome_pending`.
602
+ //
603
+ // A departure is kept APART from foreign traffic all the way into the disclosure. The two are one
604
+ // CLASSIFICATION and two EXPLANATIONS — both drop out of the count, but "the page left for another
605
+ // document" and "somebody else's host answered" send a reader to different next steps, and one
606
+ // list holding both makes the second the only thing the first can be read as.
699
607
  const ignoredDevTooling = [];
608
+ const ignoredForeign = [];
609
+ const ignoredDepartures = [];
700
610
  const events = allEvents.filter((e) => {
701
611
  if (!NET_TYPES.has(e.type))
702
612
  return true;
703
- const url = str(e.data['url']);
704
- if (!isDevToolingUrl(url))
705
- return true;
706
- if (url !== undefined && !ignoredDevTooling.includes(url))
707
- ignoredDevTooling.push(url);
708
- return false;
613
+ // Classified by `urlForMatch`, DISCLOSED by `url`: redaction rewrites sensitive path segments at
614
+ // emit time (`/auth/token/refresh-context` -> `/auth/token/[REDACTED]`), and a declared
615
+ // `background` pattern is matched with `String.includes` — so classifying on the displayed URL
616
+ // would let a redacted segment put the endpoint back in the in-flight count, which is the defect
617
+ // this whole branch exists to fix. The haystack is the raw request; the transcript gets the
618
+ // displayed one. Same division of labour `urlContains` uses at the top of this file.
619
+ const matchUrl = urlForMatch(e.data);
620
+ const shown = str(e.data['url']);
621
+ if (isDevToolingUrl(matchUrl)) {
622
+ if (shown !== undefined && !ignoredDevTooling.includes(shown))
623
+ ignoredDevTooling.push(shown);
624
+ return false;
625
+ }
626
+ // Departure first: a departure to the app's own origin is still a request whose result nobody
627
+ // will see, and reporting it as somebody else's host would be the wrong explanation.
628
+ if (isDeparture(e.data)) {
629
+ if (shown !== undefined && !ignoredDepartures.includes(shown))
630
+ ignoredDepartures.push(shown);
631
+ return false;
632
+ }
633
+ if (isForeignTraffic(matchUrl, scope?.appUrl, scope?.background ?? [])) {
634
+ if (shown !== undefined && !ignoredForeign.includes(shown))
635
+ ignoredForeign.push(shown);
636
+ return false;
637
+ }
638
+ return true;
709
639
  });
710
- const disclosure = 0 === ignoredDevTooling.length ? {} : { ignoredDevTooling };
640
+ // Three separate lists rather than one: "the framework talking about itself", "the page left", and
641
+ // "somebody else's host" are three different facts about a window, and a reader told only one of
642
+ // them has to guess which it was.
643
+ const disclosure = {
644
+ ...(0 === ignoredDevTooling.length ? {} : { ignoredDevTooling }),
645
+ ...(0 === ignoredForeign.length ? {} : { ignoredForeign }),
646
+ ...(0 === ignoredDepartures.length ? {} : { ignoredDepartures }),
647
+ };
711
648
  // A request that STARTED (NET_PENDING) but never completed (NET_REQUEST with the same id) is
712
649
  // still in flight — the page is NOT settled no matter how quiet the DOM has gone. Without this,
713
650
  // a slow save reads as "settled" the instant its spinner stops mutating the DOM: the exact
@@ -86,6 +86,30 @@ function placeholderValue(input) {
86
86
  const value = input['value'];
87
87
  return 'string' === typeof value && UNFILLED_PLACEHOLDER.test(value) ? value : undefined;
88
88
  }
89
+ /**
90
+ * The one member of an `allOf`/`anyOf`/`not` every issue points into, when there is exactly one.
91
+ *
92
+ * Read at the outer level, a member's mistake was reported as the combinator's: "allOf accepts:
93
+ * predicates … unknown field satisfies" for a `satisfies` on a nested `element`, which sends the
94
+ * agent to fix the wrong level. Re-parsing that member names its own kind, fields and example.
95
+ */
96
+ function onlyChildBlamed(input, issues) {
97
+ if ('object' !== typeof input || null === input)
98
+ return undefined;
99
+ const heads = new Set(issues.map((issue) => 'predicates' === issue.path[0] && 'number' === typeof issue.path[1]
100
+ ? `predicates.${issue.path[1]}`
101
+ : 'predicate' === issue.path[0] && 1 < issue.path.length
102
+ ? 'predicate'
103
+ : ''));
104
+ const [head] = heads;
105
+ if (1 !== heads.size || undefined === head || '' === head)
106
+ return undefined;
107
+ const [field, index] = head.split('.');
108
+ const record = input;
109
+ const container = record[field ?? ''];
110
+ const value = undefined === index ? container : container?.[Number(index)];
111
+ return undefined === value ? undefined : { path: head, value };
112
+ }
89
113
  export function parsePredicate(input) {
90
114
  const unfilled = placeholderValue(input);
91
115
  if (unfilled !== undefined) {
@@ -98,9 +122,18 @@ export function parsePredicate(input) {
98
122
  const parsed = PredicateSchema.safeParse(input);
99
123
  if (parsed.success)
100
124
  return parsed.data;
101
- const kind = 'object' === typeof input && null !== input && 'kind' in input
102
- ? String(input['kind'])
103
- : 'unknown';
125
+ const child = onlyChildBlamed(input, parsed.error.issues);
126
+ if (child !== undefined) {
127
+ try {
128
+ parsePredicate(child.value);
129
+ }
130
+ catch (error) {
131
+ if (error instanceof Error)
132
+ throw new Error(`${child.path}: ${error.message}`);
133
+ }
134
+ }
135
+ const asWritten = kindAsWritten(input);
136
+ const kind = 'string' === typeof asWritten ? asWritten : 'unknown';
104
137
  // Bounded on purpose: a union rejection can produce one issue per member, and pasting all of them
105
138
  // back is how the zod array became unreadable in the first place.
106
139
  const issues = parsed.error.issues.slice(0, 3).map(describeIssue).join('; ');
@@ -126,20 +159,127 @@ const CALL_LEVEL_FIELDS = [
126
159
  'target',
127
160
  'intent',
128
161
  ];
162
+ /** The fields that carry a predicate inside a predicate — `anyOf`/`allOf`, and `not`. */
163
+ const NESTED_PREDICATE_FIELDS = ['predicates', 'predicate'];
164
+ /**
165
+ * `type`, read as the discriminator when — and only when — `kind` is absent.
166
+ *
167
+ * Spelled here rather than imported: core keeps this constant private, and `core-coupling-only-
168
+ * shrinks` counts every name the engine borrows — a one-word alias is not worth a permanent one.
169
+ * The two are held together by a test instead, so a change to the alias fails here rather than
170
+ * silently reintroducing the `kind "unknown"` reading this fixes.
171
+ */
172
+ const KIND_ALIAS = 'type';
173
+ /**
174
+ * How many locator clauses one rejection carries before the rest are counted instead.
175
+ *
176
+ * A rejected `anyOf`/`allOf` produces one clause per invalid member, and unlike the three-issue
177
+ * limit on schema errors these had none — so a single tool error could grow into the same sentence
178
+ * repeated until the advice that was asked for was the hardest thing in it to find.
179
+ */
180
+ const MAX_LOCATOR_CLAUSES = 3;
181
+ /** The clause for a `ref` beside a `query` that already holds a locator. */
182
+ const ELEMENT_REF_DELETE_CLAUSE = '`ref` is not a field of an `element` predicate: the locator already sits in `query`, ' +
183
+ 'so delete the `ref` rather than moving it up beside `until`.';
184
+ /** The clause for a `ref` written where the locator belongs, naming the fields `query` accepts. */
185
+ function elementRefMoveClause(queryFields) {
186
+ return ('`ref` is not a locator on an `element` predicate: element predicates take `query` ' +
187
+ `(${queryFields}), not \`ref\` — put the locator inside \`query\`; a raw element ref ` +
188
+ 'belongs in `query.scope`.');
189
+ }
190
+ /**
191
+ * Whether a written `query` actually carries a locator.
192
+ *
193
+ * `{}` is accepted by the schema and locates nothing, so presence of the key is not the question.
194
+ * Reading it as "the locator is already there" told the caller to delete the only target it had.
195
+ */
196
+ function carriesLocator(query) {
197
+ return 'object' === typeof query && null !== query && 0 < Object.keys(query).length;
198
+ }
199
+ /**
200
+ * The kind as written, reading core's `type` spelling when `kind` is absent.
201
+ *
202
+ * `PredicateSchema` accepts `type` as the discriminator whenever `kind` is missing — core normalises
203
+ * it in `applyPredicateAliases` before parsing, and an explicit `kind` still wins. Reading `kind`
204
+ * alone here is how `{ type: 'element', ref: 'e1' }` came back as `kind "unknown"` carrying the very
205
+ * #1374 advice the canonical spelling no longer gets. One reader for the sentence and the clause, so
206
+ * the two cannot disagree about which kind was written.
207
+ */
208
+ function kindAsWritten(input) {
209
+ if ('object' !== typeof input || null === input)
210
+ return undefined;
211
+ const obj = input;
212
+ return obj['kind'] !== undefined ? obj['kind'] : obj[KIND_ALIAS];
213
+ }
129
214
  /** The clause naming where a misplaced call argument goes, or '' when nothing was misplaced. */
130
215
  function misplacedCallFields(input) {
216
+ const clauses = [...new Set(misplacedClauses(input))];
217
+ // Bounded like the issue list above, and for the same reason: one rejected `anyOf` can carry an
218
+ // invalid `element` per member, and a clause each turns one tool error into a wall of the same
219
+ // sentence — which buries the advice instead of delivering it. The count is named rather than
220
+ // silently dropped, so a caller with a genuinely long list knows to look at the members.
221
+ const shown = clauses.slice(0, MAX_LOCATOR_CLAUSES);
222
+ const rest = clauses.length - shown.length;
223
+ if (0 < rest)
224
+ shown.push(`${rest} more predicate${1 === rest ? '' : 's'} need the same fix.`);
225
+ return 0 === shown.length ? '' : ` ${shown.join(' ')}`;
226
+ }
227
+ /**
228
+ * The clauses for this object, plus the same reading one level down.
229
+ *
230
+ * `anyOf`/`allOf` wrap a predicate, and wrapping the first `element` assertion of a session in one is
231
+ * an ordinary way to write it — so the `ref`-as-locator answer has to reach that level too, or the
232
+ * fix holds only for the spellings that happen to be top-level. The walk is bounded by the number of
233
+ * clauses reported rather than by depth: the schema nests without limit, and a depth cutoff answered
234
+ * `allOf → not → anyOf → element` with the error this change exists to explain.
235
+ */
236
+ function misplacedClauses(input) {
131
237
  if ('object' !== typeof input || null === input)
132
- return '';
238
+ return [];
239
+ const obj = input;
133
240
  const written = Object.keys(input);
134
- const misplaced = CALL_LEVEL_FIELDS.filter((field) => written.includes(field));
135
- if (0 === misplaced.length)
136
- return '';
137
- const list = misplaced.join(', ');
138
- // Named as a MOVE, not as a removal. Deleting the field is the reading of "unknown field" that
139
- // costs the caller the thing it asked for.
140
- return (` ${list} ${1 === misplaced.length ? 'is an argument' : 'are arguments'} of the CALL, not of ` +
141
- `the predicate: ${1 === misplaced.length ? 'move it' : 'move them'} up beside \`until\` rather ` +
142
- 'than dropping it — nesting is why the predicate did not parse.');
241
+ const clauses = [];
242
+ // `element` is the one kind where a `ref` is not a call argument one level too deep but a locator
243
+ // written in the wrong place: the locator nests under `query`, so the retry is to move it inside
244
+ // `query` — not up beside `until`. That advice is misdirection here: on `act_and_wait` moving a
245
+ // `ref` up retargets the ACTION, and `reticle_assert` has no `until` at all, so the caller loses
246
+ // its target and still does not parse. Named as the field to write instead, so the retry keeps it.
247
+ //
248
+ // `ref: undefined` is not a locator written in the wrong place, so the clause keys off a value
249
+ // rather than off the key being present.
250
+ const kind = kindAsWritten(input);
251
+ const refIsLocator = 'string' === typeof kind && PredicateKind.ELEMENT === kind && obj['ref'] !== undefined;
252
+ if (refIsLocator) {
253
+ // The locator may ALREADY be in `query`, and then the only thing to do is delete the extra
254
+ // `ref`. "Put the locator inside `query`" would send the caller to rewrite a field that is
255
+ // already right — a worse retry than the one it replaces. Derived from the schema rather than
256
+ // listed here: a stale field list is worse than none, because the agent trusts it and retries
257
+ // into the same wall.
258
+ //
259
+ // An EMPTY `query` is not a locator: `{}` parses, and deleting the `ref` as told would leave
260
+ // the predicate with no target at all. So the "already there" reading keys off `query`
261
+ // carrying at least one field, not off the key being present.
262
+ const queryFields = (predicateNestedFieldsFor(PredicateKind.ELEMENT)['query'] ?? []).join('/');
263
+ clauses.push(carriesLocator(obj['query']) ? ELEMENT_REF_DELETE_CLAUSE : elementRefMoveClause(queryFields));
264
+ }
265
+ const misplaced = CALL_LEVEL_FIELDS.filter((field) => written.includes(field) && !(refIsLocator && 'ref' === field));
266
+ if (0 < misplaced.length) {
267
+ const list = misplaced.join(', ');
268
+ // Named as a MOVE, not as a removal. Deleting the field is the reading of "unknown field" that
269
+ // costs the caller the thing it asked for.
270
+ clauses.push(`${list} ${1 === misplaced.length ? 'is an argument' : 'are arguments'} of the CALL, not of ` +
271
+ `the predicate: ${1 === misplaced.length ? 'move it' : 'move them'} up beside \`until\` rather ` +
272
+ 'than dropping it — nesting is why the predicate did not parse.');
273
+ }
274
+ for (const field of NESTED_PREDICATE_FIELDS) {
275
+ const child = obj[field];
276
+ if (child === undefined)
277
+ continue;
278
+ for (const nested of Array.isArray(child) ? child : [child]) {
279
+ clauses.push(...misplacedClauses(nested));
280
+ }
281
+ }
282
+ return clauses;
143
283
  }
144
284
  /**
145
285
  * What WOULD have worked, in the same breath as what did not.
@@ -45,6 +45,11 @@ export declare function checkRequestBody(data: Record<string, unknown>, predicat
45
45
  *
46
46
  * Ranked the way the response side ranks its own: the two nobody could have answered (redacted,
47
47
  * unrecorded, truncated) come before the one that WAS answered and came out false.
48
+ *
49
+ * `responseMismatch` is the response body of a call whose request DID satisfy the clause and whose
50
+ * response did not. When it is set, a definite request mismatch on some OTHER call is not the
51
+ * explanation and yields to it; the unknowns above still win, because the call they describe may
52
+ * be the one that would have satisfied the whole predicate.
48
53
  */
49
- export declare function requestBodyVerdict(state: RequestBodyState, predicate: NetPredicate, matchCount: number): EvalResult | undefined;
54
+ export declare function requestBodyVerdict(state: RequestBodyState, predicate: NetPredicate, matchCount: number, responseMismatch?: string): EvalResult | undefined;
50
55
  export {};